我正在尝试编写用于漂移管理的python代码,它将应用程序在JSON中的配置与预定义的键值对字典进行比较。
例:JSON中的应用程序配置:
{
"location": "us-east-1",
"properties": [
{
"type": "t2.large",
"os": "Linux"
}
],
"sgs": {
"sgid": "x-1234"
}
}示例:字典,需要比较所需的值:
{
"os": "Windows",
"location": "us-east-1"
}预期产出:
Difference is:
{
"os": "Windows"
}我一直在尝试将整个JSON (包括sub )转换为一个没有sub的dict,然后用所需dict的每个值迭代它。我能够打印所有的键,值成一行,但不能转换成一个迪克。
有更好的方法吗?或者有什么能帮到我的推荐信?
import json
def openJsonFile(file):
with open(file) as json_data:
workData = json.load(json_data)
return workData
def recursive_iter(obj):
if isinstance(obj, dict):
for item in obj.items():
yield from recursive_iter(item)
elif any(isinstance(obj, t) for t in (list, tuple)):
for item in obj:
yield from recursive_iter(item)
else:
yield obj
data = openJsonFile('file.json')
for item in recursive_iter(data):
print(item)预期产出:
{
"location": "us-east-1",
"type": "t2.large",
"os": "Linux"
"sgid": "x-1234"
}发布于 2022-07-20 22:01:47
我想这能做你想做的事。我在这个回答中使用了字典扁平化代码,只做了一个小小的修改--我将它更改为不将父字典的键与嵌套字典的键连接起来,因为这似乎是您想要的。这假设在所有嵌套字典中使用的键彼此是唯一的,在我看来,这是您的方法的一个弱点。
你问的参考资料,可以帮助你:搜索这个网站上的相关问题往往是一个有效的方式,以找到解决你自己的问题。尤其是当您想要知道的是以前可能有人问过的东西时(例如如何将嵌套的字典夷为平地),情况尤其如此。
还请注意,我编写了代码,以密切遵循PEP 8- Python代码样式指南准则--我强烈建议您阅读这些指南(并开始遵循)。
import json
desired = {
"os": "Windows",
"location": "us-east-1"
}
def read_json_file(file):
with open(file) as json_data:
return json.load(json_data)
def flatten(d):
out = {}
for key, val in d.items():
if isinstance(val, dict):
val = [val]
if isinstance(val, list):
for subdict in val:
deeper = flatten(subdict).items()
out.update({key2: val2 for key2, val2 in deeper})
else:
out[key] = val
return out
def check_drift(desired, config):
drift = {}
for key, value in desired.items():
if config[key] != value:
drift[key] = value
return drift
if __name__ == '__main__':
from pprint import pprint
config = flatten(read_json_file('config.json'))
print('Current configuration (flattened):')
pprint(config, width=40, sort_dicts=False)
drift = check_drift(desired, config)
print()
print('Drift:')
pprint(drift, width=40, sort_dicts=False)这是它产生的输出:
Current configuration (flattened):
{'location': 'us-east-1',
'type': 't2.large',
'os': 'Linux',
'sgid': 'x-1234'}
Drift:
{'os': 'Windows'}https://stackoverflow.com/questions/73053652
复制相似问题