引言
JSON(JavaScript Object Notation) 是一種輕量級的數據交換格式,獨立於編程語言的文本格式。
序列化(Serialization): 一種數據轉換方法,將結構化數據轉換爲用於存儲交換的格式,並且可以從新格式恢復原始的結構化數據。如二進制序列化。
在微服務盛行的當下,不論是與其他APP共享數據還是提供REST API接口,JSON是重要的數據交換格式。那麼在Python中,有哪些方法可以將Python Object序列化爲JSON,並且它們之間的執行速度有何差異,本來將嘗試回答這些問題。
什麼是JSON序列化:
JSON序列化:將Python內置的數據類型序列化爲JSON格式,用來數據存儲或數據交換。
import json
from sys import getsizeof
my = {'Last Name': 'XI', 'First Name': 'Dongsheng'}
print('my type is {}, size is {} bytes'.format(type(my), getsizeof(my)))
my_json = json.dumps(my)
print('after json serialize, my_json type is {}, size is {} bytes'.format(type(my_json), getsizeof(my_json)))
程序將輸出:
my type is <class 'dict'>, size is 240 bytes
after json serialize, my_json type is <class 'str'>, size is 95 bytes
JSON序列化將一個Python字典轉爲了文本格式,其他應用可以方便讀取,實現了數據交換,並且數據大小也減小爲接近原來三分之一。
Python JSON庫比較
比較Python 內置json與以下幾個庫的速度,
simplejson is a simple, fast, complete, correct and extensible JSON,It is pure Python code with no dependencies
RapidJSON is an extremely fast C++ JSON parser and serialization library
ujson is an ultra fast JSON encoder and decoder written in pure C
測試結果:
test results on my macbook pro
..::DUMPS::..
serializer time time-diff size size-diff
json: 0.626077 100.00% 7000 100.00%
simplejson: 0.840168 134.20% 7000 100.00%
rapidjson: 0.371267 59.30% 6575 93.93%
ujson: 0.291333 46.53% 6593 94.19%
..::LOADS::..
serializer time time-diff
json: 0.517331 100.00%
simplejson: 0.615013 118.88%
rapidjson: 0.470960 91.04%
ujson: 0.471361 91.11%
可以看出C語言實現的ujson在dumps json時候速度明顯快於內置的json庫。當項目中需要經常序列化JSON數據時建議使用ujson.
代碼請見 https://gist.github.com/xidongsheng/04638b476c925a34f0b8cc86dc493484