加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

如何使用Python过滤JSON数据?

发布时间:2020-12-20 11:51:16 所属栏目:Python 来源:网络整理
导读:如何使用 Python将JSON数据从input.json转换为output.json?通常,使用哪些数据结构来过滤JSON数据? 文件:input.json [{ "id":1,"a":22,"b":11},{ "id":1,"e":44,"c":77,"f":55,"d":66},{ "id":3,"b":11,"a":22},"d":44,"c":88}] 文件:output.json [{ "id"
如何使用 Python将JSON数据从input.json转换为output.json?通常,使用哪些数据结构来过滤JSON数据?

文件:input.json

[
{
    "id":1,"a":22,"b":11
},{
    "id":1,"e":44,"c":77,"f":55,"d":66
},{
    "id":3,"b":11,"a":22
},"d":44,"c":88
}
]

文件:output.json

[
{
    "id":1,"c":88
}
]

任何指针将不胜感激!

解决方法

这个想法是:

>使用json.load()将JSON内容从文件加载到Python列表
>使用collections.defaultdict和.update()方法按id重新组合数据
>使用json.dump()将结果转储到JSON文件中

执行:

import json
from collections import defaultdict

# read JSON data
with open("input.json") as input_file:
    old_data = json.load(input_file)

# regroup data
d = defaultdict(dict)
for item in old_data:
    d[item["id"]].update(item)

# write JSON data
with open("output.json","w") as output_file:
    json.dump(list(d.values()),output_file,indent=4)

现在output.json将包含:

[
    {
        "d": 66,"e": 44,"a": 22,"b": 11,"c": 77,"id": 1,"f": 55
    },{
        "b": 11,"id": 3,"d": 44,"c": 88,"a": 22
    }
]

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读