我正在研究一个要求,我必须比较两个 json 文件(master.json 和 delta.json),如果 master.json 文件中对象中的任何键:值对有任何更改,则更新对象
例如:
**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
}
]
}
如示例主机的 IP 地址在 delta.json 中更改。此更新必须移动到 master.json
生成的 master.json 应该是
**master.json**
{
[
{
host: abc
IP : 10.12.12.2
}
{
host: def
IP: 10.10.11.2
}
]
}
使用 JSON 模块,我们可以从文件中解析 json。 要使用delta
更新master
,可以使用递归函数。
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)
该函数循环访问delta
对象,并在到达"叶"时通过将其作为参数传递来更新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"
}
]
}