用python过滤json文件

时间:2019-02-13 14:43:37

标签: 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"
    }
]

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

[
    {
        "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)

我应该在这里做什么逻辑测试?

3 个答案:

答案 0 :(得分:6)

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

lon

答案 1 :(得分:1)

您也可以这样:)

>>> [{key: d[key] for key in ['Item', 'Price']} for d in input_dict] # you should rename it to `input_list` rather than `input_dict` :)
[{'Item': 10, 'Price': 8.9}, {'Item': 15, 'Price': 2.6}]

答案 2 :(得分:0)

import pprint
with open('data.json', 'r') as f:
        qe = json.load(f)
        list = []
        for item in qe['<your data>']: 
            query = (f'{item["Item"]} {item["Price"]}')

        print("query")