我见过许多项目使用simplejson模块而不是标准库中的json模块。此外,还有许多不同的simplejson模块。为什么要使用这些替代品,而不是标准库中的替代品?
当前回答
在最新版本中,Json在加载和转储两种情况下都比simplejson快
测试版本:
python: 3.6.8 json: 2.0.9 simplejson: 3.16.0
结果:
>>> def test(obj, call, data, times):
... s = datetime.now()
... print("calling: ", call, " in ", obj, " ", times, " times")
... for _ in range(times):
... r = getattr(obj, call)(data)
... e = datetime.now()
... print("total time: ", str(e-s))
... return r
>>> test(json, "dumps", data, 10000)
calling: dumps in <module 'json' from 'C:\\Users\\jophine.antony\\AppData\\Local\\Programs\\Python\\Python36-32\\lib\\json\\__init__.py'> 10000 times
total time: 0:00:00.054857
>>> test(simplejson, "dumps", data, 10000)
calling: dumps in <module 'simplejson' from 'C:\\Users\\jophine.antony\\AppData\\Local\\Programs\\Python\\Python36-32\\lib\\site-packages\\simplejson\\__init__.py'> 10000 times
total time: 0:00:00.419895
'{"1": 100, "2": "acs", "3.5": 3.5567, "d": [1, "23"], "e": {"a": "A"}}'
>>> test(json, "loads", strdata, 1000)
calling: loads in <module 'json' from 'C:\\Users\\jophine.antony\\AppData\\Local\\Programs\\Python\\Python36-32\\lib\\json\\__init__.py'> 1000 times
total time: 0:00:00.004985
{'1': 100, '2': 'acs', '3.5': 3.5567, 'd': [1, '23'], 'e': {'a': 'A'}}
>>> test(simplejson, "loads", strdata, 1000)
calling: loads in <module 'simplejson' from 'C:\\Users\\jophine.antony\\AppData\\Local\\Programs\\Python\\Python36-32\\lib\\site-packages\\simplejson\\__init__.py'> 1000 times
total time: 0:00:00.040890
{'1': 100, '2': 'acs', '3.5': 3.5567, 'd': [1, '23'], 'e': {'a': 'A'}}
版本:
python: 3.7.4 json: 2.0.9 simplejson: 3.17.0
Json在转储操作中比simplejson快,但在加载操作中两者保持相同的速度
其他回答
Json是simplejson,添加到stdlib中。但由于json是在2.6中添加的,因此simplejson具有在更多Python版本(2.4+)上工作的优势。
simplejson的更新频率也高于Python,因此如果您需要(或想要)最新版本,最好尽可能使用simplejson本身。
在我看来,一个好的做法是使用其中一种作为后备。
try:
import simplejson as json
except ImportError:
import json
下面是Python json库的比较(现在已经过时了):
比较Python的JSON模块(存档链接)
不管这个比较的结果如何,如果你使用的是Python 2.6,你应该使用标准库json。和. .否则还不如直接使用simplejson。
simplejson模块比json快1.5倍(在我的计算机上,使用simplejson 2.1.1和Python 2.7 x86)。
如果您愿意,可以尝试基准测试:http://abral.altervista.org/jsonpickle-bench.zip 在我的电脑上,simplejson比cPickle快。我也想知道你的基准!
可能,正如Coady所说,simplejson和json之间的区别在于simplejson包含_speedps .c。 那么,为什么python开发者不使用simplejson呢?
一些值在simplejson和json之间的序列化方式不同。
值得注意的是,collections.namedtuple的实例被json序列化为数组,而被simplejson序列化为对象。您可以通过将namedtuple_as_object=False传递给simplejson来覆盖此行为。转储,但默认情况下行为不匹配。
>>> import collections, simplejson, json
>>> TupleClass = collections.namedtuple("TupleClass", ("a", "b"))
>>> value = TupleClass(1, 2)
>>> json.dumps(value)
'[1, 2]'
>>> simplejson.dumps(value)
'{"a": 1, "b": 2}'
>>> simplejson.dumps(value, namedtuple_as_object=False)
'[1, 2]'
项目使用simplejson的另一个原因是内置json最初不包括它的C加速,所以性能差异是显而易见的。