Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Loads() Outputting a List Instead of an Object

I am trying to make a simple python program that outputs a random word.
I am using the requests library to pull data from this API. I am then using the loads() function from the json library to turn a string into a python object.

For some reason I am getting a list output instead of an object output, which is then causing errors.

import json
import requests

url = "https://random-words-api.vercel.app/word"

r = requests.get(url)

data = json.loads(r.text)

print(type(r.text))
print(type(data))
print(data)
word = data['word']

The output from the type(r.text) is <class 'str'>, which is correct.
The output from the type(data) is <class 'list'>, which is incorrect! Shouldn’t it return a python object?
The output from print(data) is just the random word, definition, pronounciation etc.
The output for word = data['word'] is:
word = data['word'] TypeError: list indices must be integers or slices, not str

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

So why am I getting a list rather than an object from loads()?

Also, if my question could be clearer in some way, please tell me for future reference.

>Solution :

[
  {
    "word": "Astichous",
    "definition": "Not in rows  ",
    "pronunciation": "Astikshous"
  }
]

that api is returning a list of dictionaries, it appears json.loads is working correctly. you can do word = data[0][‘word’] for you’re current example

if you wanted it to be callable like "word = data[‘word’]" you would need the api to return this:

  {
    "word": "Astichous",
    "definition": "Not in rows  ",
    "pronunciation": "Astikshous"
  }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading