Python JSON序列化

引言

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

参考文献:

  1. https://en.wikipedia.org/wiki/Serialization
  2. https://www.json.org/
  3. https://realpython.com/python-json/
  4. https://gist.github.com/cactus/4073643
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章