2013-05-11 161 views
0

大JSON文件I有一個大的JSON文件,db.json(> 100 MB)具有以下內容:閱讀磁盤

{"sitters": [["9919.html", 3, 8, 19, 47, 120, 129, 359]], "yellow": [["9945.html", 791], 
["9983.html", 1496], ["9984.html", 151]], "four": [["9971.html", 81, 403], ["9991.html", 37], 
["9995.html", 45, 225, 337], ["9975.html", 15], ["9978.html", 100], ["9948.html", 381], 
["9966.html", 228], ... 

,其中鍵是字和值的文件名,然後由索引這個詞出現在文件中。我想查詢n這個JSON文件的字數,然後檢索它們相應的文件名和位置。任何想法如何有效地做到這一點給予大文件的大小?我一直在看IJSON,但我似乎無法讓它工作。我曾嘗試:

parser = parse("db.json")                
for prefix, event, value in parser:             
    if event == 'sitters':               
     print value 

但我可能不會理解,因爲它給了我下面的錯誤如何正確地使用它:

Traceback (most recent call last): 
    File "retriever.py", line 43, in <module> 
    sys.exit(main()) 
    File "retriever.py", line 38, in main 
    for prefix, event, value in parser: 
    File "/usr/local/lib/python2.7/dist-packages/ijson/common.py", line 63, in parse 
    for event, value in basic_events: 
    File "/usr/local/lib/python2.7/dist-packages/ijson/backends/yajl2.py", line 90, in basic_parse 
    buffer = f.read(buf_size) 
AttributeError: 'str' object has no attribute 'read' 

任何幫助,不勝感激!

+2

JSON是不擅長快速查找。考慮將數據庫轉換爲更合適的格式(例如MySQL)。 – 2013-05-11 07:51:29

回答

4

你試圖解析string'db.json'該行的文件'db.json'代替:

parser = parse("db.json")                

正如你可以在錯誤信息中看到,該行buffer = f.read(buf_size)拋出此異常:

AttributeError: 'str' object has no attribute 'read'

函數parse需要一個文件:

f = open('db.json', 'r') 
parser = parse(f) 

並關閉它你的工作完成後:

f.close() 

您也可以使用with語句處理打開和關閉的過程:

with open('db.json') as f: 
    parser = parse(f) 
    # use your parser and after leaving this block indent you're done