Python更快的解析JSON大文件

提出问题
今天用python的simplejson库解析一个 >200MB 的JSON文件,发现一次decode/encode都得要 >10s,这个在我开来,实在太慢了,有没有更快的库了?


先给出我的简单测试结果
json大小:245MB
测试方法:read文件内容,然后一次decode, 一次encode

解释器simplejsonjsonujson
pypy40s多10s
cpython12s多17s多10s多

不成熟的结论: pypy+json最快


方法一:pypy+json
python自带的JSON库是用纯python代码实现的,而pypy对纯python代码的加速效果比较好。至于为什么,大家可以去google吧,很多文章解释的很好。


方法二:UltraJson
我首先想到的用C库来做JSON的解析,原因你懂的,而C语言有个JSON库叫CJSON,于是用python+cjson在google里找到了UltraJson
UltraJson是作者用C语言实现的JSON库,实际测试的效果是,整个encode的效率提升了2倍多。
使用方法:
安装:pip instal ujson

    >>> import ujson
    >>> ujson.dumps([{"key": "value"}, 81, True])
    '[{"key":"value"},81,true]'
    >>> ujson.loads("""[{"key": "value"}, 81, true]""")
    [{u'key': u'value'}, 81, True]

一些测试
Test machine:
Linux 3.13.0-66-generic x86_64 #108-Ubuntu SMP Wed Oct 7 15:20:27 UTC 2015

Versions:
CPython 2.7.6 (default, Jun 22 2015, 17:58:13) [GCC 4.8.2]
blist : 1.3.6
simplejson: 3.8.1
ujson : 1.34 (0c52200eb4e2d97e548a765d5f089858c41967b0)
yajl : 0.3.5
Array with 256 UTF-8 strings

Objectujsonyajlsimplejsonjson
encode3508.195742.003232.383309.09
decode25103.3711257.8311696.2611871.04

Array with 256 UTF-8 strings

Objectujsonyajlsimplejsonjson
encode3189.712717.142006.382961.72
decode1354.94630.54356.35344.05

Array with 256 strings

Objectujsonyajlsimplejsonjson
encode18127.4712537.3912541.2320001.00
decode23264.7012788.8525427.889352.36

Medium complex object

Objectujsonyajlsimplejsonjson
encode10519.385021.293686.864643.47
decode9676.535326.798515.773017.30

Array with 256 True values

Objectujsonyajlsimplejsonjson
encode105998.03102067.2844758.5160424.80
decode163869.9678341.57110859.36115013.90

Array with 256 dict{string, int} pairs

Objectujsonyajlsimplejsonjson
encode13471.3212109.093876.408833.92
decode16890.638946.0712218.553350.72

Dict with 256 arrays with 256 dict{string, int} pairs

Objectujsonyajlsimplejsonjson
encode50.2546.4513.8229.28
decode33.2722.1027.9110.43

Dict with 256 arrays with 256 dict{string, int} pairs, outputting sorted keys

Objectujsonyajlsimplejsonjson
encode27.197.752.39

Complex object

Objectujsonyajlsimplejsonjson
encode577.98387.81470.02
decode496.73234.44151.00145.16
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值