Home > Net >  Loads() Outputting a List Instead of an Object
Loads() Outputting a List Instead of an Object

Time:04-14

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

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.

CodePudding user response:

[
  {
    "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"
  }
  • Related