如何遍历指定JSON对象?尝试for循环(employees.items())失效
解决方法
你的JSON结构外层是一个字典,核心员工数据存在results对应的数组里。你之前用employees.items()遍历的是外层字典的键值对(只会得到('results', [员工列表])这一项),这和你想要遍历员工的需求不匹配。
下面分两种场景给出正确写法:
1. 遍历所有员工对象
假设你已经用json.loads()把JSON字符串解析成了Python字典(变量名为employees),直接遍历results数组即可:
import json # 假设json_str是你的JSON字符串 json_str = '''{ "results": [ { "added_date": "Mon, 07 Nov 2022 14:42:14 GMT", "born_date": "Mon, 07 Nov 2022 14:42:14 GMT", "cellphone": "93545887778", "father_lastname": "Mendez", "gender_id": 1, "id": 1, "mother_lastname": "Huerta", "names": "Luis", "nationality_id": 1, "picture": null, "rut": "2233229-8", "updated_date": "Mon, 07 Nov 2022 14:42:14 GMT" } ] }''' employees = json.loads(json_str) # 遍历results数组里的每个员工 for employee in employees['results']: print(employee['names'], employee['rut'])
2. 遍历每个员工的所有属性(键值对)
如果要逐个输出单个员工的所有字段和对应值,可以在遍历员工的基础上,再用.items()遍历员工字典:
for employee in employees['results']: print("--- 员工信息 ---") for key, value in employee.items(): print(f"{key}: {value}")
内容的提问来源于stack exchange,提问作者Jis
相关产品推荐
相关产品推荐

