使用 python 从 json 数据中提取值

Extract value from json data using python

在执行 API 请求后,我得到 json 'data' 如果结果方括号下的大括号,则每条记录都在不同的集合中。

我想提取数字,store/print 它们用逗号分隔。

所以要求输出

0010041,0010042

我试过使用下面的方法,但返回时出现以下错误。

TypeError: list indices must be integers or slices, not str

如果结果只有一组括号就可以正常工作,我是否必须将多个结果转换为一个,然后在 'number' 出现时提取所有结果?

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'])

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

将最后一行替换为:

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

更新:

如评论中所建议,您可以使用列表理解。所以为了得到你想要的结果,你可以这样做:

print(",".join([i['number'] for i in resp['result']]))