【问题标题】:How can I change a given JSON file (Python)?如何更改给定的 JSON 文件 (Python)?
【发布时间】:2017-06-07 16:12:55
【问题描述】:

我是 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
            ]
        } 
    ]
}

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

【问题讨论】:

    标签: python json parsing maps


    【解决方案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)
    

    【讨论】:

    • 谢谢你,OldGeeksGuide!我会试试看。我有最后一个问题:json.dump({...}, secondfile) 'secondfile' 是什么意思?
    • 哦,好的,我知道你的意思。好吧,这个 JSON 没有存储在文件中,它是 GET 请求的输出。但是我可以使用变量作为参数,而不是文件'firstfile'/'secondfile',对吗?
    • 是的,我只是用'firstfile'和'secondfile'作为输入和输出,对应原帖。你可以用你有的任何输入和你想要的任何输出来替换它们。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-18
    • 2012-12-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多