0

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}
7
  • 1
    For testing, try replacing json.load(f) with f.read() - make sure it's loading the file properly Commented Sep 6, 2016 at 3:42
  • 1
    You're opening your file in write mode with 'w+'. Remove that and try again. Commented Sep 6, 2016 at 3:42
  • @idjaw - good call, i missed that :) Commented Sep 6, 2016 at 3:46
  • 4
    Actually, your test data file is empty. "w+" truncates the file. Take a look at test.json and you will see it no longer has anything in it. Commented Sep 6, 2016 at 3:47
  • ^^ Exactly. That's the error you get when you have an empty file and try to perform a json.load in Python 2. Commented Sep 6, 2016 at 3:49

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.