简体   繁体   中英

How can I read from a list to get a dict?

I am getting an error I have never seen before, and there isn't great information on the internet on how to fix this that I could understand.

embed.add_field(name=f"Departure Airport ({res['departure']['airport']['icao']})")

The Error: TypeError: list indices must be integers or slices, not str

JSON Response: https://mystb.in/NeverSmiliesTowers.json

I understand that I am trying to read the list as a dict, but I am not so sure how to get a dict from a list. Hope you understand my issue.

Note: res is just res = await foo.json(). It just formats the response in JSON. I am also not reading this from a local file. I am reading this from an API response.

There is a common misconception that JSONs always represent dictionaries at their top level. They can represent lists as well at the top level. These are both valid JSONs:

{
  "a": "foo",
  "b": ["bar", "baz"]
}
[
  {
    "a1": "foo1",
    "b1": ["bar1", "baz1"]
  },
  {
    "a2": "foo2",
    "b2": ["bar2", "baz2"]
  }
[

The JSON sample you provided matches the second snippet above, where the top-level structure is a list(-like). Notice how the JSON begins with an opening square-bracket:

[
   {
      "greatCircleDistance":{
        ...

The res JSON is a list of dictionaries, so you need to retrieve the first dictionary from this list.

You can do so with:

res[0]['departure']['airport']['icao']

(notice how we first index the res list, which returns a dictionary that we can then get the 'departure' from.)

The response is a list, not a dict. You need to first access that list and then all the dict keys

res[0]['departure']['airport']['icao']

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