python - 用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"
}
]
我需要过滤此文件以仅显示Item
and 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)
我应该在这里做什么样的逻辑测试来做到这一点?
解决方案
假设我们可以使用dict理解,那么它将是
output_dict = [{k:v for k,v in x.items() if k in ["Item", "Price"]} for x in input_dict]
推荐阅读
- gcc - 如何使用浮点编写内联汇编
- php - 如何获取数据库记录为s 不改变固定s 在左边和右边?
- angularjs - 无法将子数据从 JSON 获取到数据表
- kubernetes - 在 Kubernetes pod 中指定内存以部署 Docker 映像
- c++ - 使用递归从子集总和中找到最大总和
- android - viewpager 第一项不显示内容
- angular - routerLinkActive 问题
- makefile - 在makefile中将Windows路径转换为Unix路径
- excel - 如何使用填充句柄在 Excel 中的行的相同步骤中复制相同的值
- reactjs - 从 SemanticUI 中的操作 onClick 中检索输入值