我需要帮助尝试使用difflib比较两个dicts。我的程序接受2个json文件,将它们转换为python dicts。然后我想在这两个dicts上使用difflib来显示两者之间的差异。在
使用difflib的正确方法是什么?在
#!/usr/bin/env python2
import json
import collections
import difflib
import pprint
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 convert(data):
if isinstance(data, basestring):
return str(data)
elif isinstance(data, collections.Mapping):
return dict(map(convert, data.iteritems()))
elif isinstance(data, collections.Iterable):
return type(data)(map(convert, data))
else:
return data
def main():
json1 = get_json()
json2 = get_json()
json1_dict = convert(json1)
json2_dict = convert(json2)
result = list(difflib.Differ.compare(json1_dict, json2_dict))
pprint.pprint(result)
if __name__ == "__main__":
main()
json示例:
^{pr2}$并在第二个文件中将ID的值更改为“1234”
我想比较一下这两者,然后得到和输出类似于:
{
"glossary": {
"title": "example glossary",
"GlossDiv": {
"title": "S",
"GlossList": {
"GlossEntry": {
- "ID": "SGML",
+ "ID": "1234",
"SortAs": "SGML",
"GlossTerm": "Standard Generalized Markup Language",
"Acronym": "SGML",
"Abbrev": "ISO 8879:1986",
"GlossDef": {
"para": "A meta-markup language, used to create markup languages such as DocBook.",
"GlossSeeAlso": [
"GML",
"XML"
]
},
"GlossSee": "markup"
}
}
}
}
}
你有一些问题。首先,您尝试使用方法
difflib.Differ.compare
,但是您将其作为一个普通函数调用-实际上您没有创建difflib.Differ
对象。第二,这个
compare
方法要求您对一个字符串序列进行操作(对于要比较的两个对象中的每一个)。您的convert
函数有时返回字符串,有时返回dict,有时返回其他内容。。。一般来说,你不能得到字符串序列。获取所需内容的自然方法是比较实际的JSON数据,因为这是一个字符串。但是,有两个问题:
您需要一个字符串序列(逐行),而不是整个JSON文档中的单个字符串,但这很简单—只需使用string
.splitlines
方法将其拆分为多行即可。您的输入可能在空白处有差异,您希望忽略这些差异。解决这一问题的简单方法是,在
load
将每个JSON文档转换为一个对象后,用dumps
为其重新创建一个字符串。其思想是,对于要比较的两个文档,您将使用相同的空白设置转储。您需要阅读文档并决定要使用的设置。相关问题 更多 >
编程相关推荐