这是一种不使用 json 模块的方法。将数据加载到变量中。然后迭代汽车键/值。如果您找到您要查找的值的键,请将其设置为新值。
另外注意:你需要关闭你的数组块,否则你上面的 json 是无效的。通常我使用在线 json 解析器来检查我的数据是否有效等(将来可能会有所帮助)。
data = {
"name":"John",
"age":30,
"cars":
[
{
"car_model": "Mustang",
"car_brand": "Ford"
},
{
"car_model": "cx-5",
"car_brand": "Mazda"
}
]
}
for cars in data['cars']:
for key, value in cars.items():
if key == "car_model" and value == "cx-5":
cars[key] = "cx-9"
print(data)
如果你想从一个文件中加载你的 json 对象,我们假设它被称为“data.json”并且和你要运行的 python 脚本在同一个目录中:
import json
with open('data.json') as json_data:
data = json.load(json_data)
for cars in data['cars']:
for key, value in cars.items():
if key == "car_model" and value == "cx-5":
cars[key] = "cx-9"
print(data)
现在,如果您想将内容写入原始文件或新文件,在这种情况下,我正在写入一个名为“newdata.json”的文件:
import json
import re
with open('data.json') as json_data:
data = json.load(json_data)
print(data)
with open('external.txt') as f:
content = f.read()
print(content)
for cars in data['cars']:
for key, value in cars.items():
if key == "car_model" and value == "cx-5":
cars[key] = content
with open('newdata.json', 'w') as outfile:
json.dump(data, outfile)