json 和 simplejson Python 模块之间有什么区别?

2025-02-20 09:23:00
admin
原创
29
摘要:问题描述:我看到许多项目使用simplejson模块而不是json标准库中的模块。此外,还有许多不同的simplejson模块。为什么要使用这些替代方案,而不是标准库中的方案?解决方案 1:json 是 simplejson,已添加到 stdlib。但由于是json在 2.6 版中添加的,因此simplejs...

问题描述:

我看到许多项目使用simplejson模块而不是json标准库中的模块。此外,还有许多不同的simplejson模块。为什么要使用这些替代方案,而不是标准库中的方案?


解决方案 1:

jsonsimplejson,已添加到 stdlib。但由于是json在 2.6 版中添加的,因此simplejson具有在更多 Python 版本(2.4+)上运行的优势。

simplejson也比 Python 更新得更频繁,所以如果你需要(或想要)最新版本,最好尽可能使用simplejson它自己。

我认为,一个好的做法是使用其中一个作为后备。

try:
    import simplejson as json
except ImportError:
    import json

解决方案 2:

我不同意其他答案:内置库json(在 Python 2.7 中)不一定比 慢simplejson。它也没有这个烦人的 unicode 错误。

这是一个简单的基准:

import json
import simplejson
from timeit import repeat

NUMBER = 100000
REPEAT = 10

def compare_json_and_simplejson(data):
    """Compare json and simplejson - dumps and loads"""
    compare_json_and_simplejson.data = data
    compare_json_and_simplejson.dump = json.dumps(data)
    assert json.dumps(data) == simplejson.dumps(data)
    result = min(repeat("json.dumps(compare_json_and_simplejson.data)", "from __main__ import json, compare_json_and_simplejson", 
                 repeat = REPEAT, number = NUMBER))
    print "      json dumps {} seconds".format(result)
    result = min(repeat("simplejson.dumps(compare_json_and_simplejson.data)", "from __main__ import simplejson, compare_json_and_simplejson", 
                 repeat = REPEAT, number = NUMBER))
    print "simplejson dumps {} seconds".format(result)
    assert json.loads(compare_json_and_simplejson.dump) == data
    result = min(repeat("json.loads(compare_json_and_simplejson.dump)", "from __main__ import json, compare_json_and_simplejson", 
                 repeat = REPEAT, number = NUMBER))
    print "      json loads {} seconds".format(result)
    result = min(repeat("simplejson.loads(compare_json_and_simplejson.dump)", "from __main__ import simplejson, compare_json_and_simplejson", 
                 repeat = REPEAT, number = NUMBER))
    print "simplejson loads {} seconds".format(result)


print "Complex real world data:" 
COMPLEX_DATA = {'status': 1, 'timestamp': 1362323499.23, 'site_code': 'testing123', 'remote_address': '212.179.220.18', 'input_text': u'ny monday for less than /u20aa123', 'locale_value': 'UK', 'eva_version': 'v1.0.3286', 'message': 'Successful Parse', 'muuid1': '11e2-8414-a5e9e0fd-95a6-12313913cc26', 'api_reply': {"api_reply": {"Money": {"Currency": "ILS", "Amount": "123", "Restriction": "Less"}, "ProcessedText": "ny monday for less than \/u20aa123", "Locations": [{"Index": 0, "Derived From": "Default", "Home": "Default", "Departure": {"Date": "2013-03-04"}, "Next": 10}, {"Arrival": {"Date": "2013-03-04", "Calculated": True}, "Index": 10, "All Airports Code": "NYC", "Airports": "EWR,JFK,LGA,PHL", "Name": "New York City, New York, United States (GID=5128581)", "Latitude": 40.71427, "Country": "US", "Type": "City", "Geoid": 5128581, "Longitude": -74.00597}]}}}
compare_json_and_simplejson(COMPLEX_DATA)
print "
Simple data:"
SIMPLE_DATA = [1, 2, 3, "asasd", {'a':'b'}]
compare_json_and_simplejson(SIMPLE_DATA)

我的系统上的结果(Python 2.7.4,Linux 64 位):

复杂的现实世界数据:

json 转储 1.56666707993 秒

simplejson 转储 2.25638604164 秒

json 加载 2.71256899834 秒

simplejson 加载 1.29233884811 秒

简单数据:

json 转储 0.370109081268 秒

simplejson 转储 0.574181079865 秒

json 加载 0.422876119614 秒

simplejson 加载 0.270955085754 秒

对于转储,json比 更快simplejson。 对于加载,simplejson更快。

由于我目前正在构建一个 Web 服务,dumps()所以更重要的是——并且始终优先使用标准库。

此外,cjson过去 4 年没有更新,所以我不会碰它。

解决方案 3:

所有这些答案都没有什么帮助,因为它们都具有时间敏感性

经过我自己的一些研究后,我发现如果你将其更新到最新版本simplejson,它确实比内置的更快。

pip/easy_install想在 ubuntu 12.04 上安装 2.3.2,但发现最新simplejson版本实际上是 3.3.0,所以我更新了它并重新运行了时间测试。

  • simplejson`json`在负载下比内置快 3 倍左右

  • simplejson`json`比dumps内置的快 30% 左右

免责声明:

上述语句是在 python-2.7.3 和 simplejson 3.3.0 (使用 c 加速) 中编写的,为了确保我的答案也不是时间敏感的,您应该运行自己的测试来检查,因为不同版本之间的差异很大;没有不敏感的简单答案。

如何判断 simplejson 中是否启用了 C 加速:

import simplejson
# If this is True, then c speedups are enabled.
print bool(getattr(simplejson, '_speedups', False))

更新:我最近遇到了一个名为ujsonsimplejson的库,它的执行速度比一些基本测试快约 3 倍。

解决方案 4:

我一直在对 json、simplejson 和 cjson 进行基准测试。

  • cjson 最快

  • simplejson 几乎与 cjson 相当

  • json 比 simplejson 慢 10 倍左右

http://pastie.org/1507411

$ python test_serialization_speed.py 
--------------------
   Encoding Tests
--------------------
Encoding: 100000 x {'m': 'asdsasdqwqw', 't': 3}
[      json] 1.12385 seconds for 100000 runs. avg: 0.011239ms
[simplejson] 0.44356 seconds for 100000 runs. avg: 0.004436ms
[     cjson] 0.09593 seconds for 100000 runs. avg: 0.000959ms

Encoding: 10000 x {'m': [['0', 1, '2', 3, '4', 5, '6', 7, '8', 9, '10', 11, '12', 13, '14', 15, '16', 17, '18', 19], ['0', 1, '2', 3, '4', 5, '6', 7, '8', 9, '10', 11, '12', 13, '14', 15, '16', 17, '18', 19], ['0', 1, '2', 3, '4', 5, '6', 7, '8', 9, '10', 11, '12', 13, '14', 15, '16', 17, '18', 19], ['0', 1, '2', 3, '4', 5, '6', 7, '8', 9, '10', 11, '12', 13, '14', 15, '16', 17, '18', 19], ['0', 1, '2', 3, '4', 5, '6', 7, '8', 9, '10', 11, '12', 13, '14', 15, '16', 17, '18', 19], ['0', 1, '2', 3, '4', 5, '6', 7, '8', 9, '10', 11, '12', 13, '14', 15, '16', 17, '18', 19], ['0', 1, '2', 3, '4', 5, '6', 7, '8', 9, '10', 11, '12', 13, '14', 15, '16', 17, '18', 19], ['0', 1, '2', 3, '4', 5, '6', 7, '8', 9, '10', 11, '12', 13, '14', 15, '16', 17, '18', 19], ['0', 1, '2', 3, '4', 5, '6', 7, '8', 9, '10', 11, '12', 13, '14', 15, '16', 17, '18', 19], ['0', 1, '2', 3, '4', 5, '6', 7, '8', 9, '10', 11, '12', 13, '14', 15, '16', 17, '18', 19], ['0', 1, '2', 3, '4', 5, '6', 7, '8', 9, '10', 11, '12', 13, '14', 15, '16', 17, '18', 19], ['0', 1, '2', 3, '4', 5, '6', 7, '8', 9, '10', 11, '12', 13, '14', 15, '16', 17, '18', 19], ['0', 1, '2', 3, '4', 5, '6', 7, '8', 9, '10', 11, '12', 13, '14', 15, '16', 17, '18', 19], ['0', 1, '2', 3, '4', 5, '6', 7, '8', 9, '10', 11, '12', 13, '14', 15, '16', 17, '18', 19], ['0', 1, '2', 3, '4', 5, '6', 7, '8', 9, '10', 11, '12', 13, '14', 15, '16', 17, '18', 19], ['0', 1, '2', 3, '4', 5, '6', 7, '8', 9, '10', 11, '12', 13, '14', 15, '16', 17, '18', 19], ['0', 1, '2', 3, '4', 5, '6', 7, '8', 9, '10', 11, '12', 13, '14', 15, '16', 17, '18', 19], ['0', 1, '2', 3, '4', 5, '6', 7, '8', 9, '10', 11, '12', 13, '14', 15, '16', 17, '18', 19], ['0', 1, '2', 3, '4', 5, '6', 7, '8', 9, '10', 11, '12', 13, '14', 15, '16', 17, '18', 19], ['0', 1, '2', 3, '4', 5, '6', 7, '8', 9, '10', 11, '12', 13, '14', 15, '16', 17, '18', 19]], 't': 3}
[      json] 7.76628 seconds for 10000 runs. avg: 0.776628ms
[simplejson] 0.51179 seconds for 10000 runs. avg: 0.051179ms
[     cjson] 0.44362 seconds for 10000 runs. avg: 0.044362ms

--------------------
   Decoding Tests
--------------------
Decoding: 100000 x {"m": "asdsasdqwqw", "t": 3}
[      json] 3.32861 seconds for 100000 runs. avg: 0.033286ms
[simplejson] 0.37164 seconds for 100000 runs. avg: 0.003716ms
[     cjson] 0.03893 seconds for 100000 runs. avg: 0.000389ms

Decoding: 10000 x {"m": [["0", 1, "2", 3, "4", 5, "6", 7, "8", 9, "10", 11, "12", 13, "14", 15, "16", 17, "18", 19], ["0", 1, "2", 3, "4", 5, "6", 7, "8", 9, "10", 11, "12", 13, "14", 15, "16", 17, "18", 19], ["0", 1, "2", 3, "4", 5, "6", 7, "8", 9, "10", 11, "12", 13, "14", 15, "16", 17, "18", 19], ["0", 1, "2", 3, "4", 5, "6", 7, "8", 9, "10", 11, "12", 13, "14", 15, "16", 17, "18", 19], ["0", 1, "2", 3, "4", 5, "6", 7, "8", 9, "10", 11, "12", 13, "14", 15, "16", 17, "18", 19], ["0", 1, "2", 3, "4", 5, "6", 7, "8", 9, "10", 11, "12", 13, "14", 15, "16", 17, "18", 19], ["0", 1, "2", 3, "4", 5, "6", 7, "8", 9, "10", 11, "12", 13, "14", 15, "16", 17, "18", 19], ["0", 1, "2", 3, "4", 5, "6", 7, "8", 9, "10", 11, "12", 13, "14", 15, "16", 17, "18", 19], ["0", 1, "2", 3, "4", 5, "6", 7, "8", 9, "10", 11, "12", 13, "14", 15, "16", 17, "18", 19], ["0", 1, "2", 3, "4", 5, "6", 7, "8", 9, "10", 11, "12", 13, "14", 15, "16", 17, "18", 19], ["0", 1, "2", 3, "4", 5, "6", 7, "8", 9, "10", 11, "12", 13, "14", 15, "16", 17, "18", 19], ["0", 1, "2", 3, "4", 5, "6", 7, "8", 9, "10", 11, "12", 13, "14", 15, "16", 17, "18", 19], ["0", 1, "2", 3, "4", 5, "6", 7, "8", 9, "10", 11, "12", 13, "14", 15, "16", 17, "18", 19], ["0", 1, "2", 3, "4", 5, "6", 7, "8", 9, "10", 11, "12", 13, "14", 15, "16", 17, "18", 19], ["0", 1, "2", 3, "4", 5, "6", 7, "8", 9, "10", 11, "12", 13, "14", 15, "16", 17, "18", 19], ["0", 1, "2", 3, "4", 5, "6", 7, "8", 9, "10", 11, "12", 13, "14", 15, "16", 17, "18", 19], ["0", 1, "2", 3, "4", 5, "6", 7, "8", 9, "10", 11, "12", 13, "14", 15, "16", 17, "18", 19], ["0", 1, "2", 3, "4", 5, "6", 7, "8", 9, "10", 11, "12", 13, "14", 15, "16", 17, "18", 19], ["0", 1, "2", 3, "4", 5, "6", 7, "8", 9, "10", 11, "12", 13, "14", 15, "16", 17, "18", 19], ["0", 1, "2", 3, "4", 5, "6", 7, "8", 9, "10", 11, "12", 13, "14", 15, "16", 17, "18", 19]], "t": 3}
[      json] 37.26270 seconds for 10000 runs. avg: 3.726270ms
[simplejson] 0.56643 seconds for 10000 runs. avg: 0.056643ms
[     cjson] 0.33007 seconds for 10000 runs. avg: 0.033007ms

解决方案 5:

simplejson 和 json 之间的某些值的序列化方式不同。

值得注意的是, 的实例collections.namedtuple被 序列化为数组,json但 被 序列化为对象simplejson。您可以通过传递namedtuple_as_object=False给 来覆盖此行为simplejson.dump,但默认情况下行为不匹配。

>>> 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]'

解决方案 6:

我发现 Python 2.7 与 simplejson 3.3.1 之间存在 API 不兼容问题,即输出结果是 str 还是 unicode 对象。例如

>>> from json import JSONDecoder
>>> jd = JSONDecoder()
>>> jd.decode("""{ "a":"b" }""")
{u'a': u'b'}

对比

>>> from simplejson import JSONDecoder
>>> jd = JSONDecoder()
>>> jd.decode("""{ "a":"b" }""")
{'a': 'b'}

如果倾向于使用 simplejson,则可以通过将参数字符串强制转换为 unicode 来解决这个问题,如下所示:

>>> from simplejson import JSONDecoder
>>> jd = JSONDecoder()
>>> jd.decode(unicode("""{ "a":"b" }""", "utf-8"))
{u'a': u'b'}

强制转换确实需要知道原始字符集,例如:

>>> jd.decode(unicode("""{ "a": "ξηθννββωφρες" }"""))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xce in position 8: ordinal not in range(128)

这是无法修复的问题 40

解决方案 7:

项目使用 simplejson 的另一个原因是内置 json 最初不包含其 C 加速,因此性能差异很明显。

解决方案 8:

内置json模块已包含在 Python 2.6 中。任何支持 Python < 2.6 版本的项目都需要有后备。在许多情况下,该后备是simplejson

解决方案 9:

以下是 Python json 库的比较(现已过时):

比较 Python 的 JSON 模块(存档链接)

无论此比较的结果如何,如果您使用的是 Python 2.6,则应使用标准库 json。否则,最好只使用 simplejson。

解决方案 10:

json似乎比simplejson最新版本的加载和转储都快

已测试的版本:

  • 蟒蛇: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'}}

对于版本:

  • 蟒蛇:3.7.4

  • json:2.0.9

  • simplejson: 3.17.0

在转储操作期间,json 比 simplejson 更快,但在加载操作期间,两者的速度相同

解决方案 11:

simplejson 模块比 json 快 1.5 倍(在我的计算机上,使用 simplejson 2.1.1 和 Python 2.7 x86)。

如果您愿意,可以尝试基准测试:http://abral.altervista.org/jsonpickle-bench.zip
在我的 PC 上,simplejson 比 cPickle 更快。我也想知道您的基准测试!

可能正如 Coady 所说,simplejson 和 json 的区别在于 simplejson 包含 _speedups.c。那么,为什么 python 开发人员不使用 simplejson?

解决方案 12:

在 python3 中,如果您有一个字符串b'bytes',则json必须先使用.decode()内容,然后才能加载它。 simplejson会处理好这个问题,所以您只需执行即可simplejson.loads(byte_string)

解决方案 13:

2024 年的更新答案。遗憾的是,其他答案已经过时了十年。

您应该使用内置import json模块。

它是同一个包。simplejson是项目名称https://github.com/simplejson/simplejson

它是在 Python 解释器json构建时附带的。

解释器捆绑的版本在那个时间点基本已经冻结。您可以安装最新的软件包以从 repo 中获取最新的更改。

当人们仍在使用 Python 2 时,simplejson 就很有用,但内置的 json 版本非常老旧,在 unicode 处理方面存在一些问题(或缺失)。您可以安装 simplejson 包,以获得在 Python 2 和 Python 3 上都能正常工作的最新库。

它不再相关并且 simplejson 的大多数用法可以被视为“过时的 python 2 兼容代码”。

所有关于性能的评论答案都已过时,因为它们与 Python 2.6 和 Python 2.7 时代的旧版 JSON 进行比较。性能改进早已实现。世界已经向前发展。有趣的是,Python 解释器(和相关的 C 库)仅在 Python 3.6 左右启用 gcc 构建优化的情况下才开始构建。

如果你正在优化绝对性能。你应该看看orjson哪些ujson是针对性能进行了优化的替代库。

解决方案 14:

我在寻找为 Python 2.6 安装 simplejson 时遇到了这个问题。我需要使用 json.load() 的“object_pairs_hook”来将 json 文件加载为 OrderedDict。由于熟悉较新版本的 Python,我没有意识到 Python 2.6 的 json 模块不包含“object_pairs_hook”,因此我必须为此安装 simplejson。从个人经验来看,这就是我使用 simplejson 而不是标准 json 模块的原因。

相关推荐
  为什么项目管理通常仍然耗时且低效?您是否还在反复更新电子表格、淹没在便利贴中并参加每周更新会议?这确实是耗费时间和精力。借助软件工具的帮助,您可以一目了然地全面了解您的项目。如今,国内外有足够多优秀的项目管理软件可以帮助您掌控每个项目。什么是项目管理软件?项目管理软件是广泛行业用于项目规划、资源分配和调度的软件。它使项...
项目管理软件   1325  
  IPD(Integrated Product Development)流程作为一种先进的产品开发管理模式,在众多企业中得到了广泛应用。它涵盖了从产品概念产生到产品退市的整个生命周期,通过整合跨部门团队、优化流程等方式,显著提升产品开发的效率和质量,进而为项目的成功奠定坚实基础。深入探究IPD流程的五个阶段与项目成功之间...
IPD流程分为几个阶段   4  
  华为作为全球知名的科技企业,其成功背后的管理体系备受关注。IPD(集成产品开发)流程作为华为核心的产品开发管理模式,其中的创新管理与实践更是蕴含着丰富的经验和深刻的智慧,对众多企业具有重要的借鉴意义。IPD流程的核心架构IPD流程旨在打破部门墙,实现跨部门的高效协作,将产品开发视为一个整体的流程。它涵盖了从市场需求分析...
华为IPD是什么   3  
  IPD(Integrated Product Development)研发管理体系作为一种先进的产品开发模式,在众多企业的发展历程中发挥了至关重要的作用。它不仅仅是一套流程,更是一种理念,一种能够全方位提升企业竞争力,推动企业持续发展的有效工具。深入探究IPD研发管理体系如何助力企业持续发展,对于众多渴望在市场中立足并...
IPD管理流程   3  
  IPD(Integrated Product Development)流程管理旨在通过整合产品开发流程、团队和资源,实现产品的快速、高质量交付。在这一过程中,有效降低成本是企业提升竞争力的关键。通过优化IPD流程管理中的各个环节,可以在不牺牲产品质量和性能的前提下,实现成本的显著降低,为企业创造更大的价值。优化产品规划...
IPD流程分为几个阶段   4  
热门文章
项目管理软件有哪些?
云禅道AD
禅道项目管理软件

云端的项目管理软件

尊享禅道项目软件收费版功能

无需维护,随时随地协同办公

内置subversion和git源码管理

每天备份,随时转为私有部署

免费试用