[英]TypeError: list indices must be integers, not str - API request
I am trying to return different parts of an API response. 我试图返回API响应的不同部分。
My data: 我的资料:
{
"data": [
"values": [
{
"value": {
"X": 7544,
"Y": 7532,
"Z": 5298
},
"end_time": "2016-11-01"
},
{
"value": {
"X": 7566,
"Y": 7579,
"Z": 5304
},
"end_time": "2016-11-02"
}
]
]
}
This is the response I get when I call 'data = json_object['data']': 这是我调用'data = json_object ['data']'时得到的响应:
[{'description': 'xxx', 'title': 'yyy', 'values': [{'end_time': '2016-12-01', 'value': {'v1': 187, 'v2': 4}}, {'end_time': '2016-12-02', 'value': {'v1': 177, 'v2': 6}}], 'name': 'name', 'id': '87654/', 'period': ‘day'}]
My code: 我的代码:
def myfunc():
r = requests.get('URL...')
json_object = r.json()
data = json_object['data']
end_time = data[0]['values'][0]['end_time']
values = data[0]['values'][0]['value']
return render_template('results.html', date = end_time, result = values)
Right now I got only first value and end_time. 现在,我只有第一个值和end_time。 All attempts to return all end with this error:
所有尝试全部返回的尝试均以以下错误结束:
TypeError: list indices must be integers, not str
Please help! 请帮忙!
似乎您正在寻找的是end_time = data[0](['values'][0]['end_time'])
-现在它正在寻找data [0] ['values'],这会导致错误因为“值”是一个字符串。
Based on your json 基于你的json
values
is a key which holds value of type array. values
是保存类型为array的values
的键。 Assuming values
is the parent element, you need 假设
values
是父元素,则需要
data["values"][0]['end_time']
If you have only one element values
, then you can do: 如果只有一个元素
values
,则可以执行以下操作:
data[0]['values'][0]['end_time']
If you have many items in your data object, you may need to loop over it like this: 如果数据对象中有很多项目,则可能需要像这样循环遍历:
for item in data:
end_time = item['values'][0]['end_time']
# ...
Moreover, in values
, you have more than one item, to read end_time
of each item inside values
, you can do: 此外,在
values
,你有一个以上的项目,阅读end_time
内每个项目的values
,你可以这样做:
for item in data:
for value in item['values']
end_time = value['end_time']
# ...
I got luck with iterating through the dict in that list with value['value']
in the end. 最后,我很幸运地遍历列表中的dict,并使用
value['value']
。 Thank you all for helping me! 谢谢大家的帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.