2015-12-25 30 views
5

我想在Python 2.7中使用json庫解析JSON多行文件。簡化樣本文件給出如下:使用Python解析多行JSON文件問題

{ 
"observations": { 
    "notice": [ 
     { 
      "copyright": "Copyright Commonwealth of Australia 2015, Bureau of Meteorology. For more information see: http://www.bom.gov.au/other/copyright.shtml http://www.bom.gov.au/other/disclaimer.shtml", 
      "copyright_url": "http://www.bom.gov.au/other/copyright.shtml", 
      "disclaimer_url": "http://www.bom.gov.au/other/disclaimer.shtml", 
      "feedback_url": "http://www.bom.gov.au/other/feedback" 
     } 
    ] 
} 
} 

我的代碼如下:

import json 

with open('test.json', 'r') as jsonFile: 
    for jf in jsonFile: 
     jf = jf.replace('\n', '') 
     jf = jf.strip() 
     weatherData = json.loads(jf) 
     print weatherData 

不過,我得到一個錯誤,如下圖所示:

Traceback (most recent call last): 
File "test.py", line 8, in <module> 
weatherData = json.loads(jf) 
File "/home/usr/anaconda2/lib/python2.7/json/__init__.py", line 339, in loads 
return _default_decoder.decode(s) 
File "/home/usr/anaconda2/lib/python2.7/json/decoder.py", line 364, in decode 
obj, end = self.raw_decode(s, idx=_w(s, 0).end()) 
File "/home/usr/anaconda2/lib/python2.7/json/decoder.py", line 380, in raw_decode 
obj, end = self.scan_once(s, idx) 
ValueError: Expecting object: line 1 column 1 (char 0) 

只是做一些測試,我修改了代碼,以便在刪除換行符和刪除前導空格和尾隨空格後,將內容寫入另一個文件(擴展名爲json)。令人驚訝的是,當我讀回後面的文件時,我沒有得到任何錯誤,解析成功。修改後的代碼如下:

import json 

filewrite = open('out.json', 'w+') 

with open('test.json', 'r') as jsonFile: 
    for jf in jsonFile: 
     jf = jf.replace('\n', '') 
     jf = jf.strip() 
     filewrite.write(jf) 

filewrite.close() 

with open('out.json', 'r') as newJsonFile: 
    for line in newJsonFile: 
     weatherData = json.loads(line) 
     print weatherData 

輸出如下:

{u'observations': {u'notice': [{u'copyright_url': u'http://www.bom.gov.au/other/copyright.shtml', u'disclaimer_url': u'http://www.bom.gov.au/other/disclaimer.shtml', u'copyright': u'Copyright Commonwealth of Australia 2015, Bureau of Meteorology. For more information see: http://www.bom.gov.au/other/copyright.shtml http://www.bom.gov.au/other/disclaimer.shtml', u'feedback_url': u'http://www.bom.gov.au/other/feedback'}]}} 

任何想法可能什麼時候換行和空格使用json庫之前被剝離?

回答

4

你會去瘋狂如果試圖解析由線JSON文件行。 json模塊具有幫助器方法來直接讀取文件對象或字符串,即loadloads方法。 load爲包含json數據的文件提取文件對象(如下所示),而loads接收包含json數據的字符串。

選項1: - 首選

import json 
with open('test.json', 'r') as jf: 
    weatherData = json.load(jf) 
    print weatherData 

選項2:

import json 
with open('test.json', 'r') as jf: 
    weatherData = json.loads(jf.read()) 
    print weatherData 

如果你正在尋找更高性能的JSON解析退房ujson

+1

謝謝@OkezieE。通過'load'加載整個文件就可以實現。 – hypersonics

5

在第一個代碼段中,您嘗試逐行解析它。你應該一次解析它。最簡單的方法是使用json.load(jsonfile)。 (因爲它是一個字符串,所以jf變量名是誤導性的)。雖然它的JSON存儲在一個行是個好主意,因爲它更簡潔

import json 

with open('test.json', 'r') as jsonFile: 
    weatherData = json.loads(jsonFile) 

:所以正確的方法來分析它。

在第二個片段中,您的問題是您將它打印爲unicode字符串,而u'string here'是python特有的。一個有效的JSON使用雙引號

+0

我試圖加載的你的方法整個文件並立即解析,但失敗。順便說一句,我已經嘗試逐行解析json文件而沒有任何問題,期望每個字典從未超過大約100個字符長。 – hypersonics

+0

對我來說,它與你提供的json很好地工作。嘗試使用Sublime JSON插件來回轉換json:https://github.com/dzhibas/SublimePrettyJson它還驗證了json,因此您可以進一步調查問題。有關更詳細的linting,請嘗試http://jsonlint.com/ – fodma1

1

僅供參考,你可以在單一with開幕詞這兩個文件:

with open('file_A') as in_, open('file_B', 'w+') as out_: 
    # logic here 
    ... 
+0

儘管此代碼可能回答此問題,但最好解釋它的作用並添加一些參考。 – dotctor

+1

這並沒有提供問題的答案。要批評或要求作者澄清,請在其帖子下方留言。 - [來自評論](/ review/low-quality-posts/10682568) –

+0

@James:同意。在回答的那一刻,我無法對問題發表評論,並感謝現在我可以: - ) –