[json] JSONDecodeError: Expecting value: line 1 column 1

I am receiving this error in Python 3.5.1.

json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Here is my code:

import json
import urllib.request

connection = urllib.request.urlopen('http://python-data.dr-chuck.net/comments_220996.json')

js = connection.read()

print(js)

info = json.loads(str(js))

image

This question is related to json python-3.x

The answer is


If you look at the output you receive from print() and also in your Traceback, you'll see the value you get back is not a string, it's a bytes object (prefixed by b):

b'{\n  "note":"This file    .....

If you fetch the URL using a tool such as curl -v, you will see that the content type is

Content-Type: application/json; charset=utf-8

So it's JSON, encoded as UTF-8, and Python is considering it a byte stream, not a simple string. In order to parse this, you need to convert it into a string first.

Change the last line of code to this:

info = json.loads(js.decode("utf-8"))

in my case, some characters like " , :"'{}[] " maybe corrupt the JSON format, so use try json.loads(str) except to check your input