[使用python从json数据中提取值

问题描述 投票:0回答:1

[执行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'])
python arrays json extract typeerror
1个回答
2
投票

错误消息很明显:您正在尝试访问词典列表,但操作不正确。

将最后一行替换为:

for i in resp['result']:
    print(i['number'])

更新:

如注释中所建议,您可以使用列表理解。因此,要获得所需的结果,可以执行以下操作:

print(",".join([i['number'] for i in resp['result']]))
© www.soinside.com 2019 - 2024. All rights reserved.