[英]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 : 我的json数据有效,我将JSON文件编码更改为utf-8,但仍然无法正常工作,这是我的代码:
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: 这是我的test.json数据:
{"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: 首先,让我们确认您的json数据有效地模拟了文件内容,如下所示:
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: 该脚本仅打印DONE
,这意味着您的文件内容是有效的JSON,因此,如果我们看一下您的脚本:
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. 代码的主要问题是您正在使用w+
写模式,该模式会截断文件(您应该使用读取模式),因此文件对象不再有效。 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.