如何使用Python过滤JSON数据? [英] How to filter JSON data using Python?

查看:267
本文介绍了如何使用Python过滤JSON数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用Python将JSON数据从 input.json 转换为 output.json ?一般来说,用于过滤JSON数据的数据结构是什么?

How to convert JSON data from input.json to output.json using Python? In general, what data structures are used for filtering JSON data?

文件:input.json

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

文件:output.json

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

任何指针将不胜感激!

推荐答案

想法是:

  • use json.load() to load the JSON content from file to a Python list
  • regroup the data by the id, using collections.defaultdict and .update() method
  • use json.dump() to dump the result into the JSON file

实施:

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

这篇关于如何使用Python过滤JSON数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆