如何在python中过滤json数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27189892/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to filter json array in python
提问by Majid Zandi
That is the current json array I have. I want get all json objects that type=1
那是我当前拥有的 json 数组。我想获取 type=1 的所有 json 对象
before filter:
过滤前:
[
{
"type": 1
"name" : "name 1",
},
{
"type": 2
"name" : "name 2",
},
{
"type": 1
"name" : "name 3"
},
]
after filter:
过滤后:
[
{
"type": 1
"name" : "name 1",
},
{
"type": 1
"name" : "name 3"
},
]
please help.
请帮忙。
采纳答案by Joaquin Sargiotto
The following snippet of code does exactly what you want, but BEWARE that your input (as written in the question) is not a valid json string, you can check here: http://jsonlint.com.
以下代码片段完全符合您的要求,但请注意您的输入(如问题中所写)不是有效的 json 字符串,您可以在此处查看:http: //jsonlint.com。
import json
input_json = """
[
{
"type": "1",
"name": "name 1"
},
{
"type": "2",
"name": "name 2"
},
{
"type": "1",
"name": "name 3"
}
]"""
# Transform json input to python objects
input_dict = json.loads(input_json)
# Filter python objects with list comprehensions
output_dict = [x for x in input_dict if x['type'] == '1']
# Transform python object back into json
output_json = json.dumps(output_dict)
# Show json
print output_json

