gpt4 book ai didi

python - 在 Python 中递归检查 JSON 对象

转载 作者:行者123 更新时间:2023-12-01 00:36:17 25 4
gpt4 key购买 nike

我有许多不同结构的 JSON 文件,它们都具有多个“嵌套”级别。我需要检查可能出现在对象中任何位置的某些键并更新它们。

正在努力处理“嵌套”元素

我有一些代码是通过谷歌搜索(我是Python新手)拼凑而成的,并且已经尝试过这两种方法实例(值,字典)和类型(值)是字典

但是在任何情况下日志都不会显示“迭代更深”。

def iterate(dictionary):
for key, value in dictionary.items():
print('key {} -> value {}'.format(key, value))
#if logic to update specific values
print('Dict new value {}'.format(value))
if isinstance(value, dict):
#if type(value) is dict:
print('Iterating deeper. Key {}'.format(key))
dictionary[key] = iterate(value)
return(dictionary)

简单的 JSON 示例:

myObj = {
"name":"John",
"age":30,
"cars": {
"car1":"Ford",
"car2":"BMW",
"car3":"Fiat"
}
}

我希望看到“迭代更深入。关键汽车”打印出来

最佳答案

更新:

def iterjson(data):
for key, value in data.items():
if (update_condition):
data[key] = new_value

print('key {} -> value {}'.format(key, value))
if isinstance(value, dict):
print('Iterating deeper. Key {}'.format(key))
yield from iterjson(value)
else:
yield value

迭代而不更新:

def iterjson(data):
for key, value in data.items():
print('key {} -> value {}'.format(key, value))
if isinstance(value, dict):
print('Iterating deeper. Key {}'.format(key))
yield from iterjson(value)
else:
yield value

如果您还想使用 list 进行迭代:

def iterjson(data):
for key, value in data.items():
print('key {} -> value {}'.format(key, value))
if isinstance(value, dict):
print('Iterating deeper. Key {}'.format(key))
yield from iterjson(value)
elif isinstance(value, list):
for i in value:
yield i
else:
yield value

关于python - 在 Python 中递归检查 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57744326/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com