Skip to main content
 首页 » 编程设计

python之用python过滤json文件

2025年05月04日14fff_TT

如何过滤 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" 
    } 
] 

我需要过滤此文件以仅显示Item 和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) 

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

请您参考如下方法:

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

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