Search code examples
jsonpython-3.xlistflaskresponse

Accessing object elements in list


I get the response of a server:

r = requests.get(my_url)
print(r.text)
json_response = json.loads(r.text)
print(type(json_response))

I am using json.loads() to convert the string into json. However, the response has this format:

[{"element_info":{"data":201863539001,......]

I want to access element_info.data. I tried accessing it with json_response.element_info.data but i got AttributeError: 'list' object has no attribute 'bkdn_elem_info'.

I also tried content = r.read() and i got AttributeError: 'Response' object has no attribute 'read'.


Solution

  • You cannot access the elements of a dictionary in python with '.' operator as in javascript. You have to use the square bracket notation as below to access the elements

    json_response[0]["element_info"]["data"]