I need help trying to use difflib to compare two dicts. My program takes 2 json files, converts them to python dicts. Then I would like to use difflib on the two dicts to display the differences between the two.
Whats the correct way of using difflib to go about this?
#!/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 example:
{
"glossary": {
"title": "example glossary",
"GlossDiv": {
"title": "S",
"GlossList": {
"GlossEntry": {
"ID": "SGML",
"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"
}
}
}
}
}
And change the value of ID to "1234" in a second file
I wanted to compare the two and get and output of something like:
{
"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"
}
}
}
}
}
Differ.compareis an instance method. Is there any purpose to yourconvertfunction other than to get rid of unicode strings? Anyway,difflibworks on sequences of lines, not on arbitrary objects like dictionaries. What sort of content do your json files have? What do you expect your program's output to be like?