Python requests.json() showing errors

Viewed 889
import requests
r = requests.get("http://link-short.rf.gd/codes/hello/package.json")
r.json()

The codes are showing me

File "c:\file.py", line 3, in <module>
    r.json()
  File "C:\Users\88019\AppData\Local\Programs\Python\Python39\lib\site-packages\requests\models.py", line 910, in json
    return complexjson.loads(self.text, **kwargs)
  File "C:\Users\88019\AppData\Local\Programs\Python\Python39\lib\json\__init__.py", line 346, in loads
    return _default_decoder.decode(s)
  File "C:\Users\88019\AppData\Local\Programs\Python\Python39\lib\json\decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Users\88019\AppData\Local\Programs\Python\Python39\lib\json\decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

What is the problem and how can I solve that ?

3 Answers

The problem is that JSON is not invalid. To be precise, the problem is not the link, but the file_2.txt file. So you have 2 solution: Check the file_2.text file and get a file that is correctly JSON, because this file is not. Or if you really can't get a JSON file, you can modify your code by inserting a request that applies to your file, because when you run your r (therefore a Requests) it makes assumptions about the encoding of the response based on the headers http. To change the encoding you can replace r.json () with r.text (), so like this:

import requests

r = requests.get ("http://link-short.rf.gd/codes/hello/file_2.txt")
r.text()

UPDATE

I noticed that you later changed the link in the question. Try these

import json
import requests

r = requests.get (http://link-short.rf.gd/codes/hello/package.json)
data = r.json()

or this, because it converts a string to access your JSON

import json
import requests

r = requests.get (http://link-short.rf.gd/codes/hello/package.json)
data = json.loads(r.text)

well http://link-short.rf.gd/codes/hello/file_2.txt does not supply a json.

So you could supply a link to a json file

You cannot call r.json() if r is not a json file. Since your URL points to some file_2.txt, it is not in json() format and hence r.json() will not help you.

Consider using r.text() instead

Related