2014-11-21 59 views
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方法解析之前做相同的文件。任何人都可以向我解釋爲什麼會出現這種情況,以及我是否錯誤地瞭解錯誤的原因?

非常感謝!

回答

0

當您在文件句柄上調用read()時,其當前讀取位置被提前到文件末尾。這反映了底層文件描述符的行爲。您可以通過jsondata.seek(0, 0)重置爲文件的開頭。