I have two json objects as below:
json.json
{
"access_points": [
{
"ssid": "MyAP",
"snr": 63,
"channel": 11
},
{
"ssid": "YourAP",
"snr": 42,
"channel": 1
},
{
"ssid": "HisAP",
"snr": 54,
"channel": 6
}
]
}
json_.json
{
"access_points": [
{
"ssid": "MyAP",
"snr": 82,
"channel": 11
},
{
"ssid": "YourAP",
"snr": 42,
"channel": 6
},
{
"ssid": "HerAP",
"snr": 71,
"channel": 1
}
]
}
And as you can see above, the values have changed a bit as:
- MyAP’s SNR has changed from 63 to 82
- YourAP’s channel has changed from 1 to 6
- HisAP is removed from the list
- HerAP is added to the list with SNR 71 and channel 1
I need to track the above and my expected output should be:
Following items have changed: ==========================
1. MyAP’s SNR has changed from 63 to 82
2. YourAP’s channel has changed from 1 to 6
3. HisAP is removed from the list
4. HerAP is added to the list with SNR 71 and channel 1
========================================================
This is what I have been trying to compare the keys but I am stuck how I can compare each nested values:
def checkIfEquals(obj):
if isinstance(obj, dict):
return sorted((k, checkIfEquals(v)) for k, v in obj.items())
if isinstance(obj, list):
return sorted(checkIfEquals(x) for x in obj)
else:
return obj
def test():
# JSON string
with open('/Users/jananath/Desktop/Int/tmp/json.json') as data_file:
one = json.load(data_file)
with open('/Users/jananath/Desktop/Int/tmp/json_.json') as data_file:
two = json.load(data_file)
areTheytheSame = checkIfEquals(one) == checkIfEquals(two)
if areTheytheSame:
print("Same")
else:
for key in two.keys():
value = two[key]
if key not in one:
print("found new key {0} with value {1}".format(key, value))
else:
#check if values are not same
if one[key] != value: print("for key %s values are different" % key)
Can someone please help ?