Python的JSON模块显示出意外的行为

时间:2014-11-21 04:09:36

标签: 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.load(jsondata))
    print "The basic_config after updating with JSON:", basic_config
jsondata.close()

basic_config 对象是一个字典对象,它在程序的早些时候在某处构建,并且在这里我想添加从解析用户获得的新字典键值对#39 ;将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方法有关。任何人都可以向我解释为什么会这样,以及我是否误解了错误的原因?

非常感谢!

1 个答案:

答案 0 :(得分:0)

当您在文件句柄上调用read()时,其当前读取位置会前进到文件末尾。这反映了底层文件描述符的行为。您可以通过jsondata.seek(0, 0)重置为文件的开头。