Python表现出的意外行为';s JSON模块
我正在围绕一个软件工具编写一个简单的包装程序,这个包装程序将解析一个JSON配置文件,该文件将由用户编码,作为用户指定程序特定配置的一种方式 在程序中,我有以下代码行:Python表现出的意外行为';s JSON模块,python,json,file,dictionary,contextmanager,Python,Json,File,Dictionary,Contextmanager,我正在围绕一个软件工具编写一个简单的包装程序,这个包装程序将解析一个JSON配置文件,该文件将由用户编码,作为用户指定程序特定配置的一种方式 在程序中,我有以下代码行: with open(os.path.join(args.config_bin_dir, 'basic_config.json'), 'r') as jsondata : print "JSON File contents:", jsondata.read() basic_config.update(json.lo
with open(os.path.join(args.config_bin_dir, 'basic_config.json'), 'r') as jsondata :
print "JSON File contents:", jsondata.read()
basic_config.update(json.load(jsondata))
print "The basic_config after updating with JSON:", basic_config
jsondata.close()
basic_config对象是一个dictionary对象,它是在程序前面的某个地方构建的,在这里,我想将解析用户JSON配置文件获得的新dictionary键值对添加到basic_config dictionary对象中
当程序运行时,我得到以下错误,其中一部分如下:
File "path/to/python/script.py", line 42, in main
basic_config.update(json.load(jsondata))
File "/usr/lib/python2.7/json/__init__.py", line 290, in load
**kw)
File "/usr/lib/python2.7/json/__init__.py", line 338, in loads
return _default_decoder.decode(s)
File "/usr/lib/python2.7/json/decoder.py", line 366, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python2.7/json/decoder.py", line 384, in raw_decode
raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded
我对这个错误感到非常困惑,但我注意到,只要我删除行print“JSON File contents:”,jsondata.read()
,并以以下方式运行代码,它就会消失:
with open(os.path.join(args.config_bin_dir, 'basic_config.json'), 'r') as jsondata :
# print "JSON File contents:", jsondata.read()
basic_config.update(json.load(jsondata))
print "The basic_config after updating with JSON:", basic_config
jsondata.close()
或
如果我注释掉json.load
方法后的行,仍然会得到相同的错误:
with open(os.path.join(args.config_bin_dir, 'basic_config.json'), 'r') as jsondata :
print "JSON File contents:", jsondata.read()
basic_config.update(json.load(jsondata))
# print "The basic_config after updating with JSON:", basic_config
jsondata.close()
所以我猜这与在解析同一个文件之前调用JSON文件对象上的read
方法有关。请任何人向我解释一下为什么会这样,以及我是否误解了错误的原因
多谢各位 在文件句柄上调用read()
时,其当前读取位置将前进到文件末尾。这反映了底层文件描述符的行为。您可以通过jsondata.seek(0,0)
重置为文件的开头
with open(os.path.join(args.config_bin_dir, 'basic_config.json'), 'r') as jsondata :
print "JSON File contents:", jsondata.read()
basic_config.update(json.load(jsondata))
# print "The basic_config after updating with JSON:", basic_config
jsondata.close()