Python的快速JSON解析器:cyjson

jopen 9年前

Python的快速JSON解析器:cyjson

这是一个采用Cython编写的封装类。其底层库 cJSON 由 Dave Gamble采用C语言开发。

import cyj    parser = cyj.cyj()    #loading data into cyjson and parsing it internally  #returns True on success and False on failure  parser << '{"ab":"test","c":[1,2,{"x":["y","f","w",[6,7,8,10]]},4],"s":{"y":["llüöll",1,false,true]}}'    #information such as types, keywords and item size  print parser.root_info()    #getting information on elements, raises cyJSON_* exception on error  print parser >> ('c',2)    #converting items into python objects  for i in parser.root_info()["keys"]:      print parser( ( str(i), ) )

loading

parser << "JSON" # will be converted -> .replace("\'","\"")

converting to python object

This is not efficient, because it converts the whole structure into python objects.

parser.get_root()

retrieving info

Instead of converting to python object, we can collect some information and extract the target value directly from C layer which is faster and more efficient.

>>> parser.root_info()  {'keys': [u'ab', u'c', u's'], 'types': ['str', 'list', 'dict'], 'size': 3}  >>> parser >> ('c',)  {'keys': [], 'types': ['num', 'num', 'dict', 'num'], 'size': 4}

get value

>>> parser( ('c',1) )  2  >>> parser( ('c',2 ) )  {'x': [u'y', u'f', u'w', [6, 7, 8, 10]]}

install

git clone --recursive https://github.com/mitghi/cyjson/  cd ./cyjson/cJSON; make ; make install ; cd ..  python setup.py build_ext --inplace
项目地址: https://github.com/mitghi/cyjson