Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

json

I am trying to import a file which was saved using json.dumps and contains tweet coordinates:

{
    "type": "Point", 
    "coordinates": [
        -4.62352292, 
        55.44787441
    ]
}

My code is:

>>> import json
>>> data = json.loads('/Users/JoshuaHawley/clean1.txt')  

But each time I get the error:

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

I want to end up extracting all the coordinates and saving them separately to a different file so they can then be mapped, but this seemingly simple problem is stopping me from doing so. I have looked at answers to similar errors but don't seem to be able to apply it to this. Any help would be appreciated as I am relatively new to python.

like image 682
JTH Avatar asked Nov 29 '15 16:11

JTH


People also ask

What does Expecting value line 1 column 1 char 0 mean Python?

The Python "json. decoder. JSONDecodeError: Expecting value: line 1 column 1 (char 0)" occurs when we try to parse something that is not valid JSON as if it were. To solve the error, make sure the response or the file is not empty or conditionally check for the content type before parsing.

How do I fix JSON decode error?

JSONDecodeError: Extra data" occurs when we try to parse multiple objects without wrapping them in an array. To solve the error, wrap the JSON objects in an array or declare a new property that points to an array value that contains the objects.


2 Answers

json.loads() takes a JSON encoded string, not a filename. You want to use json.load() (no s) instead and pass in an open file object:

with open('/Users/JoshuaHawley/clean1.txt') as jsonfile:
    data = json.load(jsonfile)

The open() command produces a file object that json.load() can then read from, to produce the decoded Python object for you. The with statement ensures that the file is closed again when done.

The alternative is to read the data yourself and then pass it into json.loads().

like image 51
Martijn Pieters Avatar answered Oct 11 '22 07:10

Martijn Pieters


I had similar error: "Expecting value: line 1 column 1 (char 0)"

It helped for me to add "myfile.seek(0)", move the pointer to the 0 character

with open(storage_path, 'r') as myfile:
if len(myfile.readlines()) != 0:
    myfile.seek(0)
    Bank_0 = json.load(myfile)
like image 23
Sergey_M Avatar answered Oct 11 '22 05:10

Sergey_M