[英]Flat json to nested json python
I want to convert input json to nested json defined, I am not able to think of any json library which help me achieve this我想将输入 json 转换为定义的嵌套 json,我想不出任何 json 库来帮助我实现这一目标
Input 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}]
output json output json
{
"USD": {
"John": {
"Boston": [
{
"Marks": 100
}
]
},
Current scenario based on value Currency,Name,state,marks当前场景基于值 Currency,Name,state,marks
The nested json can be put upto n level if required such as Name and state and marks or it can be Name, curreny, state and marks or Name,curreny and marks如果需要,嵌套的 json 可以放置到 n 级,例如名称和 state 和标记,或者它可以是名称、货币、state 和标记或名称、货币
So you want currency > name > state > list of marks.所以你想要货币 > 名称 > state > 标记列表。
One solution would be to create the structure using defaultdict
s, and then just add to it.一种解决方案是使用
defaultdict
创建结构,然后添加。
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})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.