Python的快速JSON解析器:cyjson

jopen 8年前發布 | 39K 次閱讀 cyjson JSON開發包

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

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!