【问题标题】:Is there a way to to convert a nested json array into multiple arrays? [duplicate]有没有办法将嵌套的 json 数组转换为多个数组? [复制]
【发布时间】:2020-10-12 20:00:20
【问题描述】:

有没有办法转换一个看起来像这样的json:

{
    "id": "1",
    "object": [{
        "object_1": "hi",
        "object_2": "hello"
    },
    {
        "object_1": "hello",
        "object_2": "hi"
    }]
}

到我可以在每个字典中存储父 ID 而不必像这样更改名称的地方?

{
"id": "1",
"object_1": "hi",
"object_2": "hello"
},
{"id": "1",
"object_1": "hi",
"object_2": "hello"
}

【问题讨论】:

  • 当然可以!你试过什么?

标签: python json python-3.x dictionary


【解决方案1】:

有很多方法可以转换字典。例如,使用生成器:

d = {
    "id": "1",
    "object": [{
        "object_1": "hi",
        "object_2": "hello"
    },
    {
        "object_1": "hello",
        "object_2": "hi"
    }]
}
    
def flatten_dict(d):
    for o in d['object']:
        yield {
            'id': d['id'],
            **o
        }

print(list(flatten_dict(d)))

打印:

[{'id': '1', 'object_1': 'hi', 'object_2': 'hello'}, {'id': '1', 'object_1': 'hello', 'object_2': 'hi'}]

【讨论】:

  • 正是我要找的东西,非常感谢@andrejKesely,这是一个重复的问题,因为它之前已经介绍过,但是您保持对象名称相同,这正是我所需要的
猜你喜欢
  • 2022-01-13
  • 1970-01-01
  • 1970-01-01
  • 2019-03-16
  • 2022-01-04
  • 2021-04-06
  • 1970-01-01
  • 2020-08-03
  • 2022-01-09
相关资源
最近更新 更多