-2

python newbie:

json1.json

{
    "key1": {
        "s11": 1,
        "s12": 2,
        "s13": "abc"
    },

    "key2": {
        "s21": [1, 2, 3, 4],
        "s22": {
            "s221": {
                "s2211": "abc"
            }
        }
    },
    "key3": "name1"
}

json2.json

{
    "key1": {
        "p12": 2,
        "p13": "abc",
        "s11": 1
    },

    "key2": {
        "ps22": {
          "ps221": {
            "ps2211": "abc"
          }
        },
        "ps21": ["1", "2", "3", "4"],
        "ps23" : "abc",
        "ps24":1,
        "s21": [1,2,3,4]
    }
}

I am trying to compare the two json object names; json1.json and json2.json and want to list out the difference in the object names
eg., list out the below differences
1. key3 is missing from json2 that is present in json1 --> Got this with below code
2. key2.s22 is changed to key2.ps22 and key1.s12 to key1.p12
3. will not bother the key2.s22.s221.s2211 different to key2.ps22.ps221.ps2211 as want to capture initial hierarchical differences

Can someone please help me with the appropriate methods or commands to capture these differences?

I could get the differences in the object names with below code.

d1=json.load(open("json1.json"))
d2=json.load(open("json2.json"))
s1=set(d1.keys()) - set(d2.keys())
print(s1)

o/p -> {'key3'}

but my requirement is to get the difference in the next level hierarchy i.e.,
key2.s22 is changed to key2.ps22
key2.s21 is changed to key2.ps21

TGRS
  • 1
  • 1
  • 2
    Possible duplicate of [Difference in a dict](https://stackoverflow.com/questions/6632244/difference-in-a-dict) – Stephen Rauch Feb 06 '18 at 07:15
  • There's no builtin or standard way to do it. You'll have to implement (or research to see if it's done) a recursive function to do that. – Akhorus Feb 10 '18 at 03:13
  • agreed, so far I was able to check the unique keynames within objects by recursive checking as below – TGRS Feb 10 '18 at 13:04

1 Answers1

0
import json

d1=json.load(open("1.json"))
d2=json.load(open("2.json"))

d11=list(d1.keys())
d22=list(d2.keys())

print(set(d1.keys())^set(d2.keys()))
chk_list = ["key2"]  # picking the keys to get the assymetry keynmaes within keynames

for i in chk_list:
    print(sorted(list(d1[i].keys())))
    print(sorted(list(d2[i].keys())))
    print(set(d1[i].keys()) ^ set(d2[i].keys()))

output is

{'key3'}
['s21', 's22']
['ps21', 'ps22', 'ps23', 'ps24', 's21']
{'ps23', 's22', 'ps24', 'ps22', 'ps21'}
TGRS
  • 1
  • 1