1

I checked this thread on comparing JSON objects.

JSON a:

{
    "errors": [
        {"error": "invalid", "field": "email"},
        {"error": "required", "field": "name"}
    ],
    "success": false
}

` JSON b: with extra field

{
    "errors": [
        {"error": "invalid", "field": "email"},
        {"error": "required", "field": "name"},
        { "key1": : "value2", }

    ],
    "success": false
}

I want to compare these 2 jsons in python such that it will tell me

  1. IF JSON is same and found extra key-value pair then it should give result that Found new field: { "key1: : "value2", } and rest of the json is same.

    1. If JSON is exactly same means if keys are matching in order then it will say TRUE.
    2. If JSON Keys are same but values are different then it will say, for the below keys the values are different.
Darius
  • 10,762
  • 2
  • 29
  • 50
born2Learn
  • 1,253
  • 5
  • 14
  • 25

2 Answers2

1

you can do something like this,

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
Prakhar
  • 2,270
  • 19
  • 26
1

If you want to print only the difference in subjson (and not the whole structure from the root), you may want to use recursive request

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
riverfall
  • 820
  • 7
  • 23