简体   繁体   中英

TypeError: list indices must be integers, not str - API request

I am trying to return different parts of an API response.

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

[{'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. 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

values is a key which holds value of type array. Assuming values is the parent element, you need

data["values"][0]['end_time']

If you have only one element values , then you can do:

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:

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. Thank you all for helping me!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM