在python中展开JSON文件

2024-09-29 23:15:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我想将JSON展平,这样即使是嵌套的JSON也可以获得列的值。

这是JSON文件:

"columns": {
    "id": {
      "$type": "pyint"
    },
    "name": {
      "firstname": {
        "$type": "pystr",
        "$props": {
          "min_chars": 10,
          "max_chars": 20
        }
      },
      "lastname": {
        "$type": "pystr",
        "$props": {
          "min_chars": 10,
          "max_chars": 20
        }
      }
    },
    "price": {
      "$type": "pyfloat",
      "$props": {
        "right_digits": 2,
        "positive": true
      }
    }
}

输出应如下所示:

^{pr2}$

只要保持项目之间的对应关系,要存储的数据结构并不重要。


Tags: columns文件nameidjsontypefirstnameprops
1条回答
网友
1楼 · 发布于 2024-09-29 23:15:16

您可以使用递归查找sub dicts中的'$type'键的函数:

def recurse(d):
    for k, v in d.items():
        if isinstance(v, dict):
            if '$type' in v:
                yield k, v['$type']
            yield from recurse(v)

因此,假设您的JSON对象加载到变量ddict(recurse(d))将返回:

^{pr2}$

相关问题 更多 >

    热门问题