如何更改给定的JSON文件(Python)?

时间:2017-06-07 16:12:55

标签: python json parsing maps

我是Python新手,我目前正在构建一个python应用程序(通过Flask)。我已经到了一半,但我需要将给定的JSON文件更改为其他结构。

我有这个JSON文件:

{
    "apps": [
        {
            "app_id": 27,
            "organization_id": "Organization_1"
        },
        {
            "app_id": 87,
            "organization_id": "Organization_2"
        },
        {
            "app_id": 88,
            "organization_id": "Organization_3"
        },
        {
            "app_id": 36,
            "organization_id": "Organization_1"
        }
    ]
}

我想把它带进一个像这样的新结构:

{
    "organizations" : [
        {
            "organization_id": "Organization_!",
            "apps": [
                27,
                36
            ]
        }, 
        {
            "organization_id": "Organization_2",
            "apps": [
                87
            ]
        }, 
        {
            "organization_id": "Organization_3",
            "apps": [
                88
            ]
        } 
    ]
}

您是否知道如何创建此输出? 谢谢你的建议!

1 个答案:

答案 0 :(得分:1)

基本上,第一种格式是从app_id到组织的映射(类似于Python dict),您希望将其转换为组织到app_id列表的映射。给定一个应用程序列表,其中每个元素将一个应用程序映射到一个组织,我将使用该列表使用dict创建新地图,即如果apps是第一个文件中的列表:

from collections import defaultdict
d = defaultdict(lambda: [])

apps = json.load(firstfile)['apps']
# d is mapping from organization_id to list of app_ids
for app in apps:
    org = app['organization_id']
    app_id = app['app_id']
    d[org].append(app_id)

# Create list of orgs from d
orgs = [{'organization_id': org, 'apps': apps} for org,apps in d.items()]

json.dump({'organizations': orgs}, secondfile)