python - 访问和替换 json 中的子类别对象

标签 python json

我想在 python 中有一个方法来查找任何我知道名称的对象,在 json 的任何层次级别。

现在,我正在尝试查找并替换以下 json 中的对象的值:

{
"world": {
    "soil": {
        "obstacleDirectory": "obstacle",
        "dimensions": {
            "width": "100",
            "length": "100",
            "depth": "1",
            "cellSize": "10"
        },

我可以访问第一个类别,"world":,或打印整个文件,但我无法使用以下命令在文件中找到对象"width": for 循环:

filename = 'run_params.json'

with open(filename, 'r+') as f:
    data  = json.load(f)

    for value in data.items():
        print value
        if "width" == data.keys():
             print "width found!"


我根本无法在 json 文件中找到 "width" 对象。

对于我应该使用 python 中的哪种类型的函数来获取这样的方法,您有什么建议吗?

最佳答案

这是一个嵌套在字典中的字典,嵌套在字典中。您必须递归地展平字典,直到找到您要查找的内容。

import json


filename = 'run_params.json'


def flatten(d):
    for k, v in d.items():
        if isinstance(v, dict):
            if 'width' in v.keys():
                return v['width']
            else:
                return flatten(v)


with open(filename, 'r+') as f:
    data  = json.load(f)
    found_it = flatten(data)
    print(found_it)

关于python - 访问和替换 json 中的子类别对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56430837/

相关文章:

python - bool 函数,用于确定白王是否处于检查棋盘上的给定位置

c++ - 如何使用来自 boost.python 的 -fPIC 编译静态库

ios - 多单元格类型 swift 4.2

json - 在 JSON 中将 sublime text 与 postgres 连接时出现错误 "psql: fe_sendauth: no password supplied"

javascript - Rails - 格式和渲染 - 它们如何工作?

Python 函数输入

python - 跨维度将 softmax 应用于矩阵中的非零元素

python - 为什么我得到 python manage.py syncdb 的错误 (IndentationError : unexpected indent)

jquery 下拉选择值

json - 使用 webpack 为 react-lottie 从主包中排除 JSON 文件