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

标签 python json

我有许多不同结构的 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/

相关文章:

python - Pandas 和 IPython 的变量可见性问题

python - 使用 Caffe 进行深度学习 - Python

python - 以django形式获取对象列表

python - 从外部范围阴影名称 xyz

python - 如何将深度嵌套的 JSON 文件转换为 CSV?

json - 带有 JSON 存储数据的 Extjs 5 XTemplate

python - 如何在lxml中编写xml文档的开头?

json - 编码不解码时如何忽略 JSON 字段

javascript - Django——将字典传递给模板并绘制折线图

json - 406 Spring MVC Json,根据请求 "accept"headers Not Acceptable