python - 在 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}
只要保持项目之间的对应关系,要存储的数据结构就无关紧要。
解决方案
您可以使用递归查找'$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'}
推荐阅读
- c# - Html Agility Pack 可以基于名称属性定位元素吗?
- python - 当键的数量与每个键的值的数量相比较小时,PySpark reduceByKey 会继续失败
- npm - 如何使用 Yarn 安装最新版本的 Next.js?
- python - 如何恢复用于生成给定哈希的字符串?
- node.js - 将 nodejs 缓冲区转换为 Uint16Array
- serial-port - 如何在 PYMODBUS(Modicon?)中塑造一个 CALL
- python - 将数据框中的列的行创建为另一个数据框中的列
- flutter - SnackBar 不显示
- google-sheets - 从其他行的组合创建行
- f# - 如何在 F# 的列表中仅保留“稳定”值