简体   繁体   中英

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}

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM