python newbie:
json1.json
{
"key1": {
"s11": 1,
"s12": 2,
"s13": "abc"
},
"key2": {
"s21": [1, 2, 3, 4],
"s22": {
"s221": {
"s2211": "abc"
}
}
},
"key3": "name1"
}
json2.json
{
"key1": {
"p12": 2,
"p13": "abc",
"s11": 1
},
"key2": {
"ps22": {
"ps221": {
"ps2211": "abc"
}
},
"ps21": ["1", "2", "3", "4"],
"ps23" : "abc",
"ps24":1,
"s21": [1,2,3,4]
}
}
我试图比较两个json对象名称; json1.json和json2.json并希望列出对象名称的差异
例如,列出以下差异
1. json1中存在json2缺少key3 - >用下面的代码得到这个
2. key2.s22更改为key2.ps22,key1.s12更改为key1.p12
3.不会打扰与key2.ps22.ps221.ps2211不同的key2.s22.s221.s2211,因为想捕获初始的层次差异
有人可以帮助我使用适当的方法或命令来捕捉这些差异吗?
我可以通过以下代码获取对象名称的差异。
d1=json.load(open("json1.json"))
d2=json.load(open("json2.json"))
s1=set(d1.keys()) - set(d2.keys())
print(s1)
o / p - > { 'KEY3'}
但我的要求是在下一级层次结构中获得差异,即,
key2.s22更改为key2.ps22
key2.s21更改为key2.ps21
答案 0 :(得分:0)
import json
d1=json.load(open("1.json"))
d2=json.load(open("2.json"))
d11=list(d1.keys())
d22=list(d2.keys())
print(set(d1.keys())^set(d2.keys()))
chk_list = ["key2"] # picking the keys to get the assymetry keynmaes within keynames
for i in chk_list:
print(sorted(list(d1[i].keys())))
print(sorted(list(d2[i].keys())))
print(set(d1[i].keys()) ^ set(d2[i].keys()))
输出
{'key3'}
['s21', 's22']
['ps21', 'ps22', 'ps23', 'ps24', 's21']
{'ps23', 's22', 'ps24', 'ps22', 'ps21'}