Re: [問題] 讀入較大的JSON檔

作者: amigcamel (阿吉amig)   2015-05-27 13:17:46
※ 引述《cal0712 (冷靜 沉著 堅持)》之銘言:
: 板上各為前輩好
: 小弟這邊有個JSON檔大概500MB左右 但一直無法順利讀入
: import ijson
: f = open('news_780796.json',mode='rb')
: for url in ijson.items(f,'url'): #"url", "timestamp"
: print(url)
: 會出現MemoryError
: 環境
: Windows XP
: Python 3.3
: 6GB RAM
: 想請問板上高手
首先,假設你的資料長這樣
[
{
"number": 0.4403575089792299,
"time": 1432698303.83547,
"uuid": "e8db5958-6603-452a-9876-0603cca59c69"
},
{
"number": 0.629411577618495,
"time": 1432698303.835664,
"uuid": "7e96f0e1-c83b-4284-bba3-0e38b6886221"
},
{
"number": 0.4546546489717844,
"time": 1432698303.835828,
"uuid": "ce41814c-58bc-419f-9233-5caa2a2e3d98"
},
........(略)........
]
: 1.如果完全不知道內部格式 想要只讀入前10筆資料怎麼個寫法呢?
import ijson
from itertools import islice
with open('news_780796.json', mode='rb') as f:
arr = ijson.items(f, 'item')
tar = list(islice(arr, 0, 5))
這邊'item'指的是該json裡面的每一個item
參考來源: http://stackoverflow.com/a/19996701/1105489
: 2.如果想要全部讀入來處理的話 應該怎麼寫呢?
這邊不是很懂您的意思
是說「全部讀進記憶體」嗎?
(你不是說這樣會有Memory Error?)
如果 是:
假設您沒有要用python內建的json模組
而是使用ijson的話
可以這樣做:
with open('news_780796.json', mode='rb') as f:
arr = ijson.items(f, '')
tar = list(arr)
這邊tar會以整個list讀進來
所以請再多一步
tar = tar[0]
參考來源: http://stackoverflow.com/a/25079108/1105489
如果 不是
如果是說要怎樣處理完這個json
可以這樣做:
with open('news_780796.json', mode='rb') as f:
arr = ijson.items(f, 'item')
while True:
try:
obj = next(arr)
# 在這裡做你想要做的事情
except StopIteration:
break
: 3.如果要處理這樣的檔案 系統的配置建議應該是怎麼樣呢?
這個已經有大大在推文中回應了
Python 要用64位元的版本
當然前提是你的作業系統也要是64位元的
詳細可參考:
http://stackoverflow.com/a/4441958/1105489
作者: cal0712 (冷靜 沉著 堅持)   2015-06-01 01:10:00
已用您的方式嘗試成功 感謝amigcamel大大的協助

Links booklink

Contact Us: admin [ a t ] ucptt.com