Andy Dufrenes
Andy Dufrenes

Reputation: 31

Don't understand why ValueError: No JSON object could be decoded occurs

I'm getting this following error

ValueError: No JSON object could be decoded

My json data is valid, i changing the JSON file encoding to utf-8, but still didn't work, this is my code :

f = open(os.path.dirname(os.path.abspath(__file__))+"/test.json", 'w+')
data = json.load(f)
pprint(data)

And this is my test.json data:

{"X":19235, "Y":19220, "Z":22685}

Upvotes: 0

Views: 314

Answers (1)

BPL
BPL

Reputation: 9863

First of all, let's confirm your json data is valid emulating the content of your file like this:

import json
from StringIO import StringIO

f = StringIO("""

{"X":19235, "Y":19220, "Z":22685}

""")

try:
    data = f.read()
    json.loads(data)
except:
    print("BREAKPOINT")

print("DONE")

The script is printing only DONE, that means the content of your file is a valid JSON, so if we take a look to your script:

f = open(os.path.dirname(os.path.abspath(__file__))+"/test.json", 'w+')
data = json.load(f)
pprint(data)

The main problem of your code is you're using w+ write mode, which is truncating the file (you should use reading mode) so the file object is not valid anymore. Try this:

f = open(os.path.dirname(os.path.abspath(__file__))+"/test.json", 'rb')
data = json.load(f)
pprint(data)

or this:

f = open(os.path.dirname(os.path.abspath(__file__))+"/test.json", 'rb')
data = json.loads(f.read())
pprint(data)

Upvotes: 1

Related Questions