作者amigcamel (阿吉amig)
看板Python
标题Re: [问题] 读入较大的JSON档
时间Wed May 27 13:17:46 2015
※ 引述《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
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 140.112.147.132
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/Python/M.1432703870.A.8D0.html
※ 编辑: amigcamel (140.112.147.131), 05/27/2015 15:22:31
1F:→ cal0712: 已用您的方式尝试成功 感谢amigcamel大大的协助 06/01 01:10