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

requests.exceptions.JSONDecodeError: Extra data: line 1 column 5 (char 4)

newb to python and requests here. I’m working with an API trying to get a JSON response but am only able to get the text version of it. My line of resp_random_1_100_int.json() returns the error:

*** requests.exceptions.JSONDecodeError: Extra data: line 1 column 4 (char 3) resp_random_1_100_int.json()

but when I run my Insomnia(similar to Postman), I’m able to get a JSON response

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

here is my code:

resp_random_1_100_int = requests.get(
            f"http://numbersapi.com/random",
   params={
                "min": "0",
                "max": "100"
            }
        )

resp_random_1_100_int.json() # <-- gives error

Here is my response from insomnia:

{
    "text": "1 is the number of Gods in monotheism.",
    "number": 1,
    "found": true,
    "type": "trivia"
}

Here is what it looks like in insomnia:
enter image description here

Also, if I only run resp_random_1_100_int.text, the response comes back with a random fact and it works but I’m not able to access the other object attributes with resp_random_1_100_int.number or resp_random_1_100_int.type

i’ve tried setting the headers with headers = {'Content-type': 'application/json'} but still no luck

Any and all help/direction is appreciated.

>Solution :

The only difference from the following code and what you posted is that I specified the content type using the headers keyword argument:

import requests
resp_random_1_100_int = requests.get(
        f"http://numbersapi.com/random",
        headers={'Content-type': 'application/json'},
        params={"min": "0", "max": "100"})

 resp_random_1_100_int.json()

Returned:

{'text': '79 is the record for cumulative weeks at #1 on the Billboard charts, held by Elvis Presley.',
 'number': 79,
 'found': True,
 'type': 'trivia'}

Here are the versions of Python and Requests I used:

  • Python 3.9.13
  • Requests 2.28.1
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