如何仅使用键比较 python 中的 2 个 JSON

How to compare 2 JSONs in python only with keys

我检查了this thread on comparing JSON objects

JSON一个:

{
    "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 中的这 2 个 json,这样它会告诉我

  1. IF JSON 相同并且找到了额外的键值对那么它应该给出结果 找到新字段:{ "key1: : "value2", } 其余 json 相同。

    1. 如果 JSON 完全相同意味着如果键按顺序匹配则它会说 TRUE。
    2. 如果JSON键相同但值不同那么它会说,对于下面的键值不同。

你可以这样做,

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

如果你只想打印 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