0
我做一个简单的包装程序周围的软件工具,而这种包装将,除其他事项外,解析会被用户编码为用户的方式JSON配置文件展出为程序指定某些配置。意外行为由Python的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.load(jsondata))
print "The basic_config after updating with JSON:", basic_config
jsondata.close()
的basic_config对象是被地方建在顶部的程序前面一个字典对象,在这里我想将通过解析用户的JSON配置文件获得的新字典键值对添加到basic_config字典对象中。
当程序运行时,我收到以下错误,其中的部分如下:
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()
或
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
方法解析之前做相同的文件。任何人都可以向我解释为什么会出现这种情况,以及我是否错误地了解错误的原因?
非常感谢!