python - 平面 json 到嵌套 json python
问题描述
我想将输入 json 转换为定义的嵌套 json,我想不出任何可以帮助我实现这一点的 json 库
输入json
[{'Name': 'John', 'state': 'Boston', 'currency': 'USD', 'marks': 100},
{'Name': 'Rohan', 'state': 'Paris', 'currency': 'EUR', 'marks': 20},
{'Name': 'Rohan', 'state': 'Lyon', 'currency': 'EUR', 'marks': 11.4},
{'Name': 'Messi', 'state': 'Madrid', 'currency': 'EUR', 'marks': 9.9},
{'Name': 'Lampard', 'state': 'London', 'currency': 'GBP', 'marks': 12.2},
{'Name': 'Lampard', 'state': 'London', 'currency': 'FBP', 'marks': 10.9}]
输出json
{
"USD": {
"John": {
"Boston": [
{
"Marks": 100
}
]
},
当前场景基于值货币、名称、状态、标记
如果需要,可以将嵌套的 json 放置到 n 级,例如 Name 和 state 和 tags 或者它可以是 Name 、 curreny 、 state 和 tags 或 Name 、curreny 和 tags
解决方案
所以你想要货币>名称>状态>标记列表。
一种解决方案是使用defaultdict
s 创建结构,然后添加到它。
from collections import defaultdict
from functools import wraps
data = [...]
def ddmaker(type_):
@wraps(dict)
def caller():
return defaultdict(type_)
return caller
# create the structure of the output
output = defaultdict(ddmaker(ddmaker(list)))
# add to it
for item in data:
currency = item["currency"]
name = item["Name"]
state = item["state"]
mark = item["marks"]
output[currency][name][state].append({'Marks': mark})
推荐阅读
- node.js - async_hooks - 为什么没有调用/清理资源
- android - 如何理解为什么 R8 不混淆代码
- server - Windows 服务器上的计划任务无法写入网络驱动器 - 错误的凭据,来自 cmd 行有效
- ansible - Ansible - 在循环中附加一个字符串 var 本身
- android-studio - 我在广播接收器中。我的问题发生在电池电量低
- c# - 使用用户输入的 SQLite 搜索
- tls1.2 - Apple Watch 中的客户端身份验证请求自动取消
- javascript - “没有名称的表单控件的值访问器”的问题
- python - 将变量和函数从 ipynb 文件导入 python 文件
- javascript - 滚动到特定元素(映射一些数据后)