首页 > 解决方案 > 用python过滤json文件

问题描述

如何过滤 json 文件以仅显示我需要的信息?

首先,我想说我对 python 和使用 JSON 还很陌生,如果之前有人问过这个问题而我忽略了它,我很抱歉。

我有一个如下所示的 JSON 文件:

[
    {
        "Store": 417,
        "Item": 10,
        "Name": "Burger",
        "Modifiable": true,
        "Price": 8.90,
        "LastModified": "09/02/2019 21:30:00"
    },
    {
        "Store": 417,
        "Item": 15,
        "Name": "Fries",
        "Modifiable": false,
        "Price": 2.60,
        "LastModified": "10/02/2019 23:00:00"
    }
]

我需要过滤此文件以仅显示Itemand Price,例如

[
    {
        "Item": 10,
        "Price": 8.90
    },
    {
        "Item": 15,
        "Price": 2.60
    }
]

我有一个看起来像这样的代码:

# Transform json input to python objects
with open("StorePriceList.json") as input_file:
    input_dict = json.load(input_file)

# Filter python objects with list comprehensions
output_dict = [x for x in input_dict if ] #missing logical test here.

# Transform python object back into json
output_json = json.dumps(output_dict)

# Show json
print(output_json)

我应该在这里做什么样的逻辑测试来做到这一点?

标签: pythonjson

解决方案


假设我们可以使用dict理解,那么它将是

output_dict = [{k:v for k,v in x.items() if k in ["Item", "Price"]} for x in input_dict]

推荐阅读