skip to Main Content

This is my current code:

limit = 1
api_url = 'https://api.api-ninjas.com/v1/facts?limit={}'.format(limit)
response = requests.get(api_url, headers={'X-Api-Key': API_KEY})

print(response.text)

I get this returned:

[{"fact": "The Canadian province of New Brunswick had a bloodless war with the US state of Maine in 1839"}]

I only want to print the fact.

response.fact doesn’t exist

print(response.fact)

I also tried loading the JSON file

import json

fact_load = json.load(response.json())
print(fact_load['fact'])

AttributeError: ‘list’ object has no attribute ‘read’

3

Answers


  1. Chosen as BEST ANSWER

    Got it

    print(response.json()[0]['fact'])
    

  2. Let me inspect the error.

    print(fact_load['fact'])
    AttributeError: 'list' object has no attribute 'read'
    

    This means that the fact_load is a list object.
    And to get content of a list obj, one must access with integer index.
    But you tried to access with a string.

    The correct answer is must be as follows.
    print(fact_load[0][‘fact’])
    (while fact_load[0] is a dict)

    Login or Signup to reply.
  3. The response text is just a text string. You can load the json reprenation usually by just using the .json() function on the request.

    The JSON will provide you a list of facts (as shown by the [] surrounding the response)

    When exporting the JSON representation it will also interpret the json object as a dict, and because Python doesn’t directly let you use dot notation to get properties of a dictionary you can use several methods of extracting the data.

    My preference for this sort of thing would be response.json()[0].get("fact", "") as you get to control the failure condition where fact wasn’t a key in the dictionary.

    Alternatively if you know "fact" is going to be a key, you can just do response.json()[0]["fact"]

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search