[英]Update one JSON with another smaller one in python
Let's say I have a very large JSON of a potentially complex structure, and I occasionally receive "update" JSON.假设我有一个非常大的潜在复杂结构的 JSON,我偶尔会收到“更新”JSON。 So, I want to update only the selected keys regardless of the nested structures:因此,无论嵌套结构如何,我只想更新选定的键:
{
"main": {
"k1": 1000000,
"k2": true,
"k3": "tam",
"k4": "gs://gcp-public-data--broad-references/hg38/v0/Homo_sapiens_assembly38.dbsnp138.vcf.idx",
"k5": {
"k5_1": "val5_1",
"k5_2": "val5_2"
}
}
}
If I got an instruction to change just k5_1 I would get JSON:如果我收到一条只更改 k5_1 的指令,我会得到 JSON:
{"main": {"k5": {"k5_2": "changed"}}}
And I want to get:我想得到:
{
"main": {
"k1": 1000000,
"k2": true,
"k3": "tam",
"k4": "gs://gcp-public-data--broad-references/hg38/v0/Homo_sapiens_assembly38.dbsnp138.vcf.idx",
"k5": {
"k5_1": "val5_1",
"k5_2": "changed"
}
}
}
Is there a smart way to do it?有没有聪明的方法来做到这一点? Thanks!谢谢!
Importing json
gives you access to read and parse json files.导入json
使您可以访问读取和解析 json 文件。 Then, json.loads returns the json as a dictionary.然后, json.loads 将 json 作为字典返回。 Then you set the keys variable then json.dumps
changes the dictionary to json then write it into the file.然后设置 keys 变量,然后json.dumps
将字典更改为 json,然后将其写入文件。
import json as j
with open(filename,'r') as f:
filedat = j.load( f.read())
filedat['main']['k5']['k5_2'] = 'changed'
with open(filename,'w') as f:
f.write(j.dumps(filedat))
A recursive solution could be a function to merge them at dict level:递归解决方案可以是在字典级别合并它们的函数:
def update_dict(dict1, dict2):
for k in dict2.keys():
if k in dict1:
v1 = dict1[k]
v2 = dict2[k]
if isinstance(v1, dict) and isinstance(v2, dict):
update_dict(v1, v2)
else:
dict1[k] = v2
import json
with open(filename1,'r') as f1:
d1 = json.load( f1.read())
with open(filename2,'r') as f2:
d2 = json.load( f2.read())
update_dict(d1, d2)
with open(filename1,'w') as f1:
json.dump(d1,f1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.