Skip to main content
 首页 » 编程设计

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

2024年11月01日9davidwang456

我是 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! 
]