我正在尝试将键值对添加到现有JSON文件中。我可以连接到父标签,如何为子项目增加价值?
JSON文件:
function mapStateToProps(state, props) {
return {
cart: state.fashion.cartDetail // changed
};
}
代码:
{
"students": [
{
"name": "Hendrick"
},
{
"name": "Mikey"
}
]
}
预期结果:
import json
with open("input.json") as json_file:
json_decoded = json.load(json_file)
json_decoded['country'] = 'UK'
with open("output.json", 'w') as json_file:
for d in json_decoded[students]:
json.dump(json_decoded, json_file)
答案 0 :(得分:4)
您可以执行以下操作以按照自己的方式操作dict
:
for s in json_decoded['students']:
s['country'] = 'UK'
json_decoded['students']
是list
的词典,您可以简单地循环访问和更新。现在您可以转储整个对象:
with open("output.json", 'w') as json_file:
json.dump(json_decoded, json_file)
答案 1 :(得分:2)
import json
with open("input.json", 'r') as json_file:
json_decoded = json.load(json_file)
for element in json_decoded['students']:
element['country'] = 'UK'
with open("output.json", 'w') as json_out_file:
json.dump(json_decoded, json_out_file)
将写入移动到第一with
段内部的输出文件。较早实现的问题是,如果json_decoded
的打开失败,将不会实例化input.json
。因此,写入输出将引发异常-NameError: name 'json_decoded' is not defined
答案 2 :(得分:0)
这会给[None, None]
,但会更新字典:
a = {'students': [{'name': 'Hendrick'}, {'name': 'Mikey'}]}
[i.update({'country':'UK'}) for i in a['students']]
print(a)