gpt4 book ai didi

python - 使用 python 解析 JSON 以根据条件获取值

转载 作者:太空宇宙 更新时间:2023-11-04 03:50:14 25 4
gpt4 key购买 nike

我是 python 的新手,正在尝试解析 json 文件并根据条件获取所需的字段。

例如,如果 status = true,则 打印名称

Json文件:

[
{
"id": "12345",
"name": "London",
"active": true,
"status": "true",
"version": "1.0",
"tags": [
]
},
{
"id": "12457",
"name": "Newyork",
"active": true,
"status": "false",
"version": "1.1",
"tags": [
]
},
]

预期输出:

名称:伦敦

请帮我解决这个问题。提前谢谢你。

最佳答案

>>> import json
>>> obj = json.loads('[ { "id": "12345", "name": "London", "active": true, "status": "true", "version": "1.0", "tags": [ ] }, { "id": "12457", "name": "Newyork", "active": true, "status": "false", "version": "1.1", "tags": [ ] } ]')
>>> print "Names:", ",".join(x["name"] for x in obj if x["status"] == "true")
Names: London

您的 JSON 无效。删除逗号如下:

[
{
"id": "12345",
"name": "London",
"active": true,
"status": "true",
"version": "1.0",
"tags": [
]
},
{
"id": "12457",
"name": "Newyork",
"active": true,
"status": "false",
"version": "1.1",
"tags": [
]
},
^__________Remove this comma!
]

关于python - 使用 python 解析 JSON 以根据条件获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21621357/

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