根据另一个json文件中的密钥匹配更新json文件值



目标:在两个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:ABTestsource.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:ABTestsource.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:ABTestcombined.json', 'w', ) as f:
json.dump(d2, f, ensure_ascii=False, indent=4)

更新2:

我成功了。更新了应答部分的工作代码。

好的,我现在已经完成了以下工作。它可以帮助人们查看类似的问题

import json
# input file for d1
with open("D:ABTestsource.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...块,使代码更加Python化和高性能。

相关内容

  • 没有找到相关文章

最新更新