【问题标题】:How to filter JSON data using Python?如何使用 Python 过滤 JSON 数据?
【发布时间】:2016-04-26 05:44:57
【问题描述】:

如何使用 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
},
{
    "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
}
]

任何指针将不胜感激!

【问题讨论】:

  • 你考虑过字典吗? :D

标签: python json


【解决方案1】:

这个想法是:

实施:

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

【讨论】:

    【解决方案2】:
    from collections import defaultdict
    
    input_list=[{"id":1, ...}, {...}]
    
    result_dict=defaultdict(dict)
    for d in input_list:
        result_dict[d['id']].update(d)
    
    output_list=result_dict.values()
    

    result_dict 是一个default dictionary,它在没有可用密钥的情况下对每次访问使用dict。所以我们遍历 input_list 并使用对应字典中的新值更新我们的 result_dict 键等于 id

    输出列表是result_dict 的转换,仅使用其值。

    使用 json module 直接处理 json 数据。

    【讨论】:

      猜你喜欢
      • 2020-12-15
      • 1970-01-01
      • 2012-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-06
      • 1970-01-01
      相关资源
      最近更新 更多