Home > Back-end >  Accessing object elements in list
Accessing object elements in list

Time:03-09

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

CodePudding user response:

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"]

CodePudding user response:

The type of json_response is list. So, you can iterate on it and access each element in it. Each element is a dictionary. So, you can use the keys:

for each_element in json_response:
    print(each_element["element_info"]["data"])

If you are not sure that these keys are available in all elements, you can use the get() method with a default value to avoid errors when the key does not exist. Here, the first operand is the key that you want to read, and the second operand can be used to define a default value:

for each_element in json_response:
    print(each_element.get("element_info", {}).get("data", ""))
  • Related