[英]Append python dictionary to json by key
using Python3 I would like to append to an existing json file, with the following format使用 Python3 我想附加到现有的 json 文件,格式如下
[{
"employee_name": "John Doe",
"employee_id": "1234",
"20200401": {
"clocked-in": "05:55:22",
"clocked-out": "15:02:22"
}
},
{
"employee_name": "Ryan Jackson",
"employee_id": "4444",
"20200401": {
"clocked-in": "05:45:10",
"clocked-out": "14:50:18"
}
}]
this new data for John Doe -- either by searching/matching by [employee_name] field or [employee_id] field.. John Doe 的新数据——通过 [employee_name] 字段或 [employee_id] 字段搜索/匹配..
"20200402": {
"clocked-in": "05:50:18",
"clocked-out": "14:30:22"
}
The result would look something like结果看起来像
[{
"employee_name": "John Doe",
"employee_id": "1234",
"20200401": {
"clocked-in": "05:55:22",
"clocked-out": "15:02:22"
},
"20200402": {
"clocked-in": "05:50:18",
"clocked-out": "14:30:22"
}
},
{
"employee_name": "Ryan Jackson",
"employee_id": "4444",
"20200401": {
"clocked-in": "05:45:10",
"clocked-out": "14:50:18"
}
}]
Thank you.谢谢你。
You can use the dict.update() method to achieve the above,您可以使用 dict.update() 方法来实现上述功能,
# python3
import json
with open('test.json') as fp:
data = json.load(fp)
new_dict = dict()
new_dict["YYYYMMDD"] = {
"key2": "val2",
"key1": "val1"
}
data.update(new_dict)
with open('test.json', 'w') as fp:
json.dump(data, fp)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.