我查了this thread on comparing JSON objects。
JSON a:
{
"errors": [
{"error": "invalid", "field": "email"},
{"error": "required", "field": "name"}
],
"success": false
}
` JSON b:带额外字段
{
"errors": [
{"error": "invalid", "field": "email"},
{"error": "required", "field": "name"},
{ "key1": : "value2", }
],
"success": false
}
我想在python中比较这两个jsons,它会告诉我
如果JSON相同并找到了额外的键值对,那么它应该给出结果 找到新字段:{“key1 ::”value2“,}和json的其余部分相同。
答案 0 :(得分:0)
你可以做这样的事情,
import json
a = json.loads(json_1) #your json
b = json.loads(json_2) #json you want to compare
#iterating through all keys in b
for key in b.keys():
value = b[key]
if key not in a:
print "found new key {0} with value {1}".format(key, value)
else:
#check if values are not same
if a[key] != value: print "for key %s values are different" % key
答案 1 :(得分:0)
如果只想打印subjson中的差异(而不打印根目录中的整个结构),则可能要使用递归请求
def json_compare(json1, json2):
#Compare all keys
for key in json1.keys():
#if key exist in json2:
if key in json2.keys():
#If subjson
if type(json1[key]) == dict:
json_compare(json1[key], json2[key])
else:
if json1[key] != json2[key]:
print "These entries are different:"
print json1[key]
print json2[key]
else:
print "found new key in json1 %r" % key
return True