使用Python替换JSON文件中的单词

2024-06-28 18:44:44 发布

您现在位置:Python中文网/ 问答频道 /正文

smpl.json文件:

[ 
   { 
      "add":"dtlz",
      "emp_details":[ 
         [ 
            "Shubham",
            "ksing.shubh@gmail.com",
            "intern"
         ],
         [ 
            "Gaurav",
            "gaurav.singh@cobol.in",
            "developer"
         ],
         [ 
            "Nikhil",
            "nikhil@geeksforgeeks.org",
            "Full Time"
         ]
      ]
   }
]

Python文件:

import json 
 with open('smpl.json', 'r') as file:
 json_data = json.load(file)
   for item in json_data["emp_details"]:
     if item[''] in ['Shubham']:
        item[''] = 'Indra'
 with open('zz_smpl.json', 'w') as file:
   json.dump(json_data, file, indent=4)

因为我的密码有问题。任何帮助都会很好

期待您的帮助。提前感谢


Tags: 文件inaddjsondataaswithopen
3条回答

下面是一个更通用的解决方案,最外层的json数组可以有多个条目(字典):

import json 
with open('test.json', 'r') as file:
  json_data = json.load(file)
  for item in json_data:
    for emp in item['emp_details']:
      if emp[0] in ['Shubham']:
        emp[0] = 'Indra'

with open('zz_smpl.json', 'w') as file:
  json.dump(json_data, file, indent=4)

首先,您需要了解列表/数组和映射数据结构,以及它们是如何用JSON表示的。说真的,为了使用JSON,您必须理解这些数据结构

空数组a1

a1 = []

带3个整数的数组

a2 = [1, 2, 3]

要解决第二个值

a2[0] is 1st value
a2[1] is 2nd value

在python中,将a2子集为第二和第三个值

a3 = a2[1:]

映射/dict是键:值对的容器。 和空映射(在python中称为dict)

d1 = {}

2对映射

d2 = { 'name' : 'Chandra Gupta Maurya' , 'age' : 2360 }
d3 = { 'street' : 'ashoka' , 'location' : 'windsor place' , 'city' : 'delhi' }

这样的价值

d2['name'] is 'Chandra Gupta Maurya'

两张地图的数组。在python(和javaScript)中执行此操作时

ad1 = [ d2, d3 ]

您正在等效地这样做:

ad1 = [ 
        { 'name' : 'Chandra Gupta Maurya' , 'age' : 2360 } ,
        { 'street' : 'ashoka' , 'location' : 'windsor place' , 'city' : 'delhi' }
      ]

所以ad1[0]

{ 'name' : 'Chandra Gupta Maurya' , 'age' : 2360 } 

显然,“emp_details”位于数组的0位置

json_data[0]['emp_details']

json_data[0]['emp_details']本身是映射数组的关键

>>> json.dumps (json_data[0]["emp_details"] , indent=2)

产生

'[\n  [\n    "Shubham",\n    "ksing.shubh@gmail.com",\n    "intern"\n  ],\n  [\n    "Gaurav",\n    "gaurav.singh@cobol.in",\n    "developer"\n  ],\n  [\n    "Nikhil",\n    "nikhil@geeksforgeeks.org",\n    "Full Time"\n  ]\n]'

>>> print ( json.dumps (json_data[0]["emp_details"], indent=2) )

产生

[
  [
    "Shubham",
    "ksing.shubh@gmail.com",
    "intern"
  ],
  [
    "Gaurav",
    "gaurav.singh@cobol.in",
    "developer"
  ],
  [
    "Nikhil",
    "nikhil@geeksforgeeks.org",
    "Full Time"
  ]
]

所以,

>>> json_data[0]["emp_details"][1]
['Gaurav', 'gaurav.singh@cobol.in', 'developer']

那么您可能希望进行替换

>>> json_data[0]["emp_details"][1][2] = 'the rain in maine falls plainly insane'
>>> json_data[0]["emp_details"][1][1] =  "I'm sure the lure in jaipur pours with furore"
>>> print ( json.dumps (json_data, indent=2) )

产生

[
  {
    "add": "dtlz",
    "emp_details": [
      [
        "Shubham",
        "ksing.shubh@gmail.com",
        "intern"
      ],
      [
        "Gaurav",
        "I'm sure the lure in jaipur pours with furore",
        "the rain in maine falls plainly insane"
      ],
      [
        "Nikhil",
        "nikhil@geeksforgeeks.org",
        "Full Time"
      ]
    ]
  }
]

您的代码有两个问题

首先,JSON包含一个数组作为根。因此,您需要获取第一项的emp_details属性:

for item in json_data[0]["emp_details"]:

然后在item变量中,需要检查索引0处的项:

if item[0] in ['Shubham']:

以下是完整的工作代码:

import json 
with open('smpl.json', 'r') as file:
  json_data = json.load(file)
  for item in json_data[0]["emp_details"]:
    if item[0] in ['Shubham']:
      item[0] = 'Indra'
with open('zz_smpl.json', 'w') as file:
  json.dump(json_data, file, indent=4)

工作repl.it链接:https://repl.it/@HarunYlmaz/python-json-write

相关问题 更多 >