首页 > 解决方案 > 在 python 中展平 JSON 文件

问题描述

我想展平 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
      }
    }
}

输出应该是这样的:

{id:pyint  , firstname:pystr   , lastname:pystr ,  price:pyfloat}

只要保持项目之间的对应关系,要存储的数据结构就无关紧要。

标签: pythonjson

解决方案


您可以使用递归查找'$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 对象已加载到 variabled中,dict(recurse(d))将返回:

{'id': 'pyint', 'firstname': 'pystr', 'lastname': 'pystr', 'price': 'pyfloat'}

推荐阅读