Reputation: 13
I'm working on a requirement where in I have to compare two json files (master.json and delta.json and update the object if there is any change for any of the key:value pair within the object in the master.json file
for e.g:
**master.json**
{
[
{
host: abc
IP : 10.10.11.1
}
{
host: def
IP: 10.10.11.2
}
]
}
**delta.json**
{
[
{
host: abc
IP: 10.12.12.2
}
]
}
As in the example IP address for host changed in the delta.json..This update has to be moved to the master.json
Resulting master.json should be
**master.json**
{
[
{
host: abc
IP : 10.12.12.2
}
{
host: def
IP: 10.10.11.2
}
]
}
Upvotes: 1
Views: 949
Reputation: 352
Using the JSON module we can parse the json from a file.
To update the master
with the delta
you can use a recursive function.
import json
master = json.loads(open("master.json", 'r', encoding='utf-8').read())
delta = json.loads(open("delta.json", 'r', encoding='utf-8').read())
def iterate_paralell(delta, master):
for k,v in delta.items():
# if it's another dict or list run recursively
if isinstance(v, dict): iterate_paralell(v, master[k])
elif isinstance(v, list):
for i in range(len(v)): iterate_paralell(v[i], master[k][i])
# update the maste with delta value
else:
master[k] = v
iterate_paralell(delta, master)
The function iterates over the delta
object and update the master
when it reaches a "leaf" by passing it along as a parameter.
master.json
{
"connections": [
{
"host": "abc",
"IP": "10.10.11.1"
},
{
"host": "def",
"IP": "10.10.11.2"
}
]
}
delta.json
{
"connections": [
{
"host": "abc",
"IP": "10.12.12.2"
}
]
}
Upvotes: 2