我创建了一个程序来比较两个 python 字典并输出两者的差异。它适用于深度为 2 或更小的字典。我应该怎么做才能处理更深度的字典以及嵌套的字典?
我遇到的另一个问题是,当我通过 get_json() 函数传递 json 数组时,它会作为列表返回。并且该程序正在使用列表而不是字典来出错。我应该如何解决这个问题?
我的程序:
#!/usr/bin/env python2
import json
def get_json():
file_name = raw_input("Enter name of JSON File: ")
with open(file_name) as json_file:
json_data = json.load(json_file)
return json_data
def print_diff(json1, json2):
for n in json1:
if n not in json2:
print('- "' + str(n) + '":')
for n in json2:
if n not in json1:
print('+ "' + str(n) + '":')
continue
if json2[n] != json1[n]:
if type(json2[n]) not in (dict, list):
print('- "' + str(n) + '" : "' + str(json1[n]))
print('+ "' + str(n) + '" : "' + str(json2[n]))
else:
if type(json2[n]) == dict:
print_diff(json1[n], json2[n])
continue
return
def main():
file1 = get_json()
print(type(file1))
file2 = get_json()
print(type(file2))
print_diff(file1, file2)
if __name__ == "__main__":
main()
字典 1 的示例:
{
"widget": {
"debug": "on",
"window": {
"title": "Sample Konfabulator Widget",
"name": "main_window",
"width": 500,
"height": 500
},
"image": {
"src": "Images/Sun.png",
"name": "sun1",
"hOffset": 250,
"vOffset": 250,
"alignment": "center"
},
"text": {
"data": "Click Here",
"size": 36,
"style": "bold",
"name": "text1",
"hOffset": 250,
"vOffset": 100,
"alignment": "center",
"onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
}
}
}
字典 2 的示例:
{
"widget": {
"debug": "on",
"window": {
"title": "Sample Konfabulator Widget",
"name": "main_window",
"width": 500,
"height": 500
},
"image": {
"src": "Images/Sun.png",
"name": "sun2",
"hOffset": 100,
"vOffset": 100,
"alignment": "center"
},
"text": {
"data": "Click Here",
"size": 36,
"style": "bold",
"name": "text1",
"hOffset": 250,
"vOffset": 100,
"alignment": "center",
"onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
}
}
}
示例输出:
Enter name of JSON File: JSON1.json
<type 'dict'>
Enter name of JSON File: JSON2.json
<type 'dict'>
- "vOffset" : "250
+ "vOffset" : "100
- "name" : "sun1
+ "name" : "sun2
- "hOffset" : "250
+ "hOffset" : "100