平面 json 到嵌套 json python

Posted

技术标签:

【中文标题】平面 json 到嵌套 json python【英文标题】:Flat json to nested json python 【发布时间】:2021-08-21 08:55:52 【问题描述】:

我想将输入 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 级,例如名称和状态和标记,或者它可以是名称、货币、状态和标记或名称、货币和标记

【问题讨论】:

n和keys是什么关系? 我们需要知道:输入是什么?使用预期输入和预期输出编辑您的问题。在你的最后一句话中,你说“最多 n 级”,然后列出 3 个级别的 2 个不同结果,以及 4 个级别的 2 个。 【参考方案1】:

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

一种解决方案是使用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)

【讨论】:

不一定输出可以有货币 > 名称 > 状态 > 标记列表它也可以像这个名称 > 货币 > 状态 > 标记列表或这个状态 > 货币 > 名称 > 标记列表。 @Coderun 什么表明它是什么形式?无论如何,您现在肯定可以弄清楚该怎么做? 是的,我可以在代码中更改它,你能指导如何打印输出@blueteeth 它没有给出确切的输出@blueteeth output 是一个字典。如果你想要 JSON,你可以使用json module in the stdlib

以上是关于平面 json 到嵌套 json python的主要内容,如果未能解决你的问题,请参考以下文章