【发布时间】:2014-01-23 00:32:41
【问题描述】:
所以我试图编写一个 python 程序,它需要 2 个 .json 文件比较内容并显示两者之间的差异。到目前为止,我的程序需要用户输入来选择两个文件并比较这两个文件就好了。我在试图弄清楚如何打印两个文件之间的实际差异时遇到了困难。
我的程序:
#!/usr/bin/env python2
import json
#get_json() requests user input to select a .json file
#and creates a python dict with the information
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
#compare_json(x,y) takes 2 dicts, and compairs the contents
#print match if equal, or not a match if there is difrences
def compare_json(x,y):
for x_values, y_values in zip(x.iteritems(), y.iteritems()):
if x_values == y_values:
print 'Match'
else:
print 'Not a match'
def main():
json1 = get_json()
json2 = get_json()
compare_json(json1, json2)
if __name__ == "__main__":
main()
我的 .json 示例:
{
"menu": {
"popup": {
"menuitem": [
{
"onclick": "CreateNewDoc()",
"value": "New"
},
{
"onclick": "OpenDoc()",
"value": "Open"
},
{
"onclick": "CloseDoc()",
"value": "Close"
}
]
},
"id": "file",
"value": "File"
}
}
【问题讨论】:
-
你想只在顶层比较还是递归比较?
-
或者如果不清楚,您可以编辑您的问题以添加要比较的第二个 json 示例吗?
-
.. 和预期的结果,请:)
-
看来你应该使用 Python sets :)
-
我想递归比较。在这两个文件中,我想将第一个文件用作“主文件”并将第二个文件与主文件进行比较。第二个具有我不想打印的主人的任何值或键。
标签: python json dictionary