首页 > 解决方案 > 平面 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

标签: pythonarraysjsonpandasdictionary

解决方案


所以你想要货币>名称>状态>标记列表。

一种解决方案是使用defaultdicts 创建结构,然后添加到它。

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})

推荐阅读