支持numpython的超高速json编解码器
nujson的Python项目详细描述
nujson:支持numpy序列化的ultrajson分叉
灵感来自Pandas' ujson
如何安装
python版本:python2.7,python3.5+
使用pip:
pip install -e git+https://github.com/caiyunapp/ultrajson.git#egg=nujson
克隆并安装:
# git clone git clone https://github.com/caiyunapp/ultrajson # Don't use `python setup.py install`# NumPy will install automatically pip install -e .
如果出现这样的错误:
ERROR: Could not find a version that satisfies the requirement numpy>=1.16.4 (from nujson) (from versions: 1.9.3)
ERROR: No matching distribution found for numpy>=1.16.4 (from nujson)
试试这个:
pip uninstall numpy pip install numpy==1.16.4 pip install nujson
示例
>>>importnumpyasnp>>>importnujsonasujson>>>a={"a":np.int64(100)}>>>ujson.dumps(a)'{"a":100}'>>>a["b"]=np.float64(10.9)>>>ujson.dumps(a)'{"a":100,"b":10.9}'>>>a["c"]=np.str_("12")>>>ujson.dumps(a)'{"a":100,"b":10.9,"c":"12"}'>>>a["d"]=np.array(list(range(10)))>>>ujson.dumps(a)'{"a":100,"b":10.9,"c":"12","d":[0,1,2,3,4,5,6,7,8,9]}'>>>a["e"]=np.repeat(3.9,4)>>>ujson.dumps(a)'{"a":100,"b":10.9,"c":"12","d":[0,1,2,3,4,5,6,7,8,9],"e":[3.9,3.9,3.9,3.9]}'
为什么要制作这样的软件包以及修改的内容
在python3上,numpy的某些数据类型不可序列化。以下是我们搜索到的一些参考资料:
- python - Why are some numpy datatypes JSON serializable and others not? - Stack Overflow
- Maximum recursion level reached in Python 3 · Issue #221 · esnme/ultrajson
- Issue 24313: json fails to serialise numpy.int64 - Python tracker
一种解决方案是类型转换,比如:int(numpy.int64)
和numpy.array.tolist()
。
但这不利于表演。在搜索Internet后,找到一个不再维护的项目Komnomnomnom/ultrajsonrecommond以使用Pandas' ujson。
我们试过了,但发现熊猫对我们的项目很重要。所以我们决定建造自己的轻型叉子。目前,esn的ujson主分支有一些问题需要解决,而master
分支是基于the v1.35 ujson。
重点是在c中转换numpy数据类型,并调用numpy的头。Commit 187bd15拥有我们为支持numpy所做的最多更改,并且Commit afedc42修复了由于clang引起的macos上的构建问题。