如何将python中的2个JSON与密钥进行比较

问题描述 投票:0回答:2

我检查了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,它会告诉我

  1. 如果JSON是相同的并且找到了额外的键值对,那么它应该给出找到新字段的结果:{“key1 ::”value2“,}和json的其余部分是相同的。 如果JSON完全相同意味着如果键按顺序匹配则表示为TRUE。 如果JSON键相同但值不同,那么它会说,对于下面的键,值是不同的。
python json python-3.x python-2.x
2个回答
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

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
© www.soinside.com 2019 - 2024. All rights reserved.