gpt4 book ai didi

python - 如何在python中过滤json数组

转载 作者:太空狗 更新时间:2023-10-29 20:33:45 26 4
gpt4 key购买 nike

那是我当前的 json 数组。我想获取所有 type=1 的 json 对象

过滤前:

[ 
{
"type": 1
"name" : "name 1",
},
{
"type": 2
"name" : "name 2",
},
{
"type": 1
"name" : "name 3"
},
]

过滤后:

[ 
{
"type": 1
"name" : "name 1",
},
{
"type": 1
"name" : "name 3"
},
]

请帮忙。

最佳答案

以下代码片段完全符合您的要求,但请注意您的输入(如问题中所写)不是有效的 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

关于python - 如何在python中过滤json数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27189892/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com