目标:匹配两个json文件中json元素值中的键和覆盖值。
输入:
源代码json文件如下:
{"CLIENT_CODE":"client-d",
"ARM_SUBSCRIPTION_ID":"abced-edfgh-dk6dkk-97dke",
"location":"easteurope"}目标json文件如下所示:
{"CLIENT_CODE":"dummy",
"ARM_SUBSCRIPTION_ID":"dummy",
"prefix":"orp",
"location":"westeurope",
"address_space":"10.0.0.0/16",
"aad_login_name":"abcd.onmicrosoft.com",
"aad_login_object_id":"dummy",
"aad_login_tenant_id":"dummy",
"bastion_allocation_method":"Static",
"bastion_sku_type":"premium",
"kv_sku_name":"premium",
"storage_account_tier":"Standard",
"storage_account_replication_type":"LRS",
"storage_account_kind":"StorageV2",
"sql_pool_sku_name":"DW100C",
"node_size_family":"MemoryOptimized"}预期输出:
{"CLIENT_CODE":"client-d",
"ARM_SUBSCRIPTION_ID":"abced-edfgh-dk6dkk-97dke",
"prefix":"orp",
"location":"easteurope",
"address_space":"10.0.0.0/16",
"aad_login_name":"abcd.onmicrosoft.com",
"aad_login_object_id":"dummy",
"aad_login_tenant_id":"dummy",
"bastion_allocation_method":"Static",
"bastion_sku_type":"premium",
"kv_sku_name":"premium",
"storage_account_tier":"Standard",
"storage_account_replication_type":"LRS",
"storage_account_kind":"StorageV2"}我尝试了什么:
import json
with open("D:\ABTest\source.json", encoding='utf-8') as f:
dataset1 = json.loads(f.read())
#print(dataset1)
with open("D:\ABTest\\target.json", encoding='utf-8') as f:
dataset2 = json.loads(f.read())
#print(dataset2)
if dataset1.keys() == dataset2.keys():
dataset2.update(dataset1)
print(dataset2)但我没有得到任何输出
Update1 :,现在我可以把它写在第三个文件中了。但无法更新相同的第二个文件,即target.json
import json
with open("D:\ABTest\source.json", encoding='utf-8') as f:
d1 = json.loads(f.read())
with open("D:\ABTest\\target.json", encoding='utf-8') as f:
d2 = json.loads(f.read())
for key in d1.keys():
if key in d2.keys():
d2[key] = d1[key]
print(d2)
with open('D:\ABTest\combined.json', 'w', ) as f:
json.dump(d2, f, ensure_ascii=False, indent=4)更新2:
我让它成功了。应答部分更新的工作代码。
发布于 2022-06-28 13:07:27
好的,我现在有后续的工作。它可以帮助人们研究类似的问题。
import json
# input file for d1
with open("D:\ABTest\source.json", encoding='utf-8') as f:
d1 = json.load(f)
# input file for d2
with open("D:\ABTest\\target.json", encoding='utf-8') as f:
d2 = json.loads(f)
# output file
with open('D:\ABTest\\target.json', 'w', ) as f:
# update values in d2 with values from d1
for key in d2:
try:
# raise an KeyError if d1 doesn't have the key
d2[key] = d1[key]
except KeyError:
pass
json.dump(d2, f, ensure_ascii=False, indent=4)
print(d2)消除if语句,并将其替换为try...except...块,使代码更具有pythonic和表演性。
https://stackoverflow.com/questions/72785953
复制相似问题