【发布时间】:2020-05-06 10:34:09
【问题描述】:
在执行 API 请求后,我得到了 json“数据”,如果结果方括号下的大括号括起来,则每条记录都在不同的集合中。
我想提取数字并用逗号分隔存储/打印它们。
所以要求输出
0010041,0010042
我尝试过使用以下内容,但它返回以下错误。
TypeError: list indices must be integers or slices, not str
如果结果只有一组括号它可以正常工作,我是否必须将多个结果转换为一个,然后在出现“数字”时提取所有时间?
import json
import sys
#load the data into an element
data={'result': [{'number': '0010041', 'day_of_week': 'monday'}, {'number': '0010042', 'day_of_week': 'tuesday'}]}
#dumps the json object into an element
json_str = json.dumps(data)
#load the json to a string
resp = json.loads(json_str)
print (resp['result'])
print (resp['result']['number'])
【问题讨论】:
-
您需要首先说明您想要数字 reg 的结果中的哪个项目。
esp['result'][0]['number'] -
在代码中添加这一行
print([i['number'] for i in resp['result']])而不是print (resp['result']['number'])。
标签: python arrays json extract typeerror