【问题标题】:Extract value from json data using python使用python从json数据中提取值
【发布时间】: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


【解决方案1】:

错误信息很清楚:您正在尝试访问字典列表,但您没有正确执行。

将最后一行替换为:

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

更新:

按照 cmets 中的建议,您可以使用列表推导。所以为了得到你想要的结果,你可以这样做:

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

【讨论】:

  • 您可以使用列表推导,这是 python 的一个强大功能,可以从字典列表中提取这些数字。 print([i['number'] for i in resp['result']])
猜你喜欢
  • 2021-11-24
  • 2017-04-16
  • 2020-06-02
  • 2021-03-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-21
  • 1970-01-01
相关资源
最近更新 更多