json과 simplejson Python 모듈의 차이점은 무엇입니까?
저는 스탠다드 라이브러리에서 모듈 대신 모듈을 사용하는 프로젝트를 많이 봐왔습니다.또한, 많은 다른 것들이 있다.simplejson
라이브러리가 하는가?왜 스탠다드 라이브러리가 아닌 이러한 대안을 사용했을까요?
json
하고 있다 simplejson
stdlib에 하지만 그 이후로는json
, 2.6에 되었습니다.simplejson
는 더 많은 Python 버전(2.4+)에서 작업할 수 있는 장점이 있습니다.
simplejson
Python보다 가 높기 Python을 사용하는 simplejson
을 사용하다
내 생각에 좋은 방법은 둘 중 하나를 예비로 사용하는 것이다.
try:
import simplejson as json
except ImportError:
import json
다른 답변에 동의하지 않을 수 없습니다. 내장 라이브러리(Python 2.7)가 반드시 보다 느리지는 않습니다.또한 이 성가신 유니코드 버그도 없습니다.
다음은 간단한 벤치마크입니다.
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 "\nSimple data:"
SIMPLE_DATA = [1, 2, 3, "asasd", {'a':'b'}]
compare_json_and_simplejson(SIMPLE_DATA)
시스템 결과(Python 2.7.4, Linux 64비트):
다음 중 하나:
1. json "1.5666707993 "
2. secondssimplejson " 2 2 22 . 25638604164 "
은 2 2.71256899834를 합니다.
1. simplejson을 합니다.다음 중 하나:
0. json "0.140109081268"
0. secondssimplejson '0.574181079865'
0. seconds (0.422876119614 초)
0. simplejson을 합니다.
핑의경경,,json
simplejson
로딩용,simplejson
더 빠릅니다.
는 웹 하고 있기 에, ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★」dumps()
는 더욱 중요하며 표준 라이브러리를 사용하는 것이 항상 권장됩니다.
ㅇㅇㅇㅇ.cjson
지난 4년 동안 업데이트되지 않았기 때문에 건드리지 않을 것입니다.
이 답변들은 모두 시간에 민감하기 때문에 별로 도움이 되지 않습니다.
제가 직접 조사를 해보니simplejson
최신 버전으로 업데이트하면 기본 제공 속도보다 훨씬 빠릅니다.
pip/easy_install
12.04를 알게 된 후2.3.2를 설치하려고 합니다.simplejson
버전이 3.3.0이기 때문에 업데이트하고 시간 테스트를 다시 실행했습니다.
simplejson
는 기본 제공 속도보다 약 3배 빠릅니다.json
을 싣고simplejson
json
면책사항:
위의 문장은 python-2.7.3 및 simplejson 3.3.0 (c speedups 포함)입니다.또, 제 답변도 시간에 민감하지 않은지 확인하기 위해서, 버전마다 매우 다르기 때문에, 당신 자신의 테스트를 실행해 확인해 주세요.시간에 민감하지 않은 쉬운 답변은 없습니다.
simplejson에서 C 스피드업이 활성화되었는지 확인하는 방법:
import simplejson
# If this is True, then c speedups are enabled.
print bool(getattr(simplejson, '_speedups', False))
업데이트: 최근 우연히 ujson이라는 라이브러리를 발견했습니다.이 라이브러리는 퍼포먼스가simplejson
몇 가지 기본적인 테스트를 거쳤습니다.
저는 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
일부 값은 simplejson과 json 간에 다르게 일련화됩니다.
님의 collections.namedtuple
에 의해 어레이로서 시리얼화 됩니다.json
, 의 by by by의 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]'
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)
프로젝트에서 simplejson을 사용하는 또 다른 이유는 빌트인 json에 원래 C 속도 업이 포함되어 있지 않았기 때문에 성능 차이가 눈에 띄었기 때문입니다.
★★json
Python 2.6 。Python < 2 . 6 버 python python python python python python python python python python python python python python python python python 。이 은 " " " 입니다.simplejson
.
다음은 Python json 라이브러리의 비교입니다.
Python용 JSON 모듈 비교(아카이브 링크)
이 비교 결과에 관계없이 Python 2.6을 사용하는 경우 표준 라이브러리 json을 사용해야 합니다.그렇지 않으면 그냥 simplejson을 쓰는 게 나을 거야
json
빠른 것 같다simplejson
version의
테스트 완료 버전:
- 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보다 빨랐지만 로드 작업 중에는 둘 다 동일한 속도를 유지했습니다.
simplejson 모듈은 json보다 1.5배 빠릅니다(내 컴퓨터에서는 simplejson 2.1.1과 Python 2.7 x 86을 사용합니다).
필요한 경우 벤치마크를 사용해 보십시오.http://abral.altervista.org/jsonpickle-bench.zip On my PC simplejson이 cPickle보다 빠릅니다.당신의 벤치마크도 알고 싶습니다!
아마도 Coady가 말했듯이 simplejson과 json의 차이점은 simplejson이 _speedups.c를 포함하고 있다는 것입니다.그렇다면 왜 비단뱀 개발자들은 simplejson을 사용하지 않는가?
python3에서 문자열이b'bytes'
,와 함께json
해야 한다.decode()
로드하기 전에 콘텐츠를 로드합니다. simplejson
이 일은 네가 알아서 하면 돼simplejson.loads(byte_string)
.
Python 2.6용 simplejson을 설치하려고 하다가 이 질문을 하게 되었습니다.json 파일을 OrderedDict로 로드하려면 json.load()의 object_pairs_hook을 사용해야 합니다.Python 2.6용 json 모듈에 'object_pairs_hook'이 포함되어 있지 않다는 것을 몰랐기 때문에 이 목적을 위해 simplejson을 설치해야 했습니다.개인적인 경험상 표준 json 모듈이 아닌 simplejson을 사용하는 이유가 여기에 있습니다.
언급URL : https://stackoverflow.com/questions/712791/what-are-the-differences-between-json-and-simplejson-python-modules
'programing' 카테고리의 다른 글
전치/해동 기능(zip 반대) (0) | 2022.09.21 |
---|---|
JUnit의 장애와 오류의 차이점은 무엇입니까? (0) | 2022.09.21 |
PHP에서 후행 0을 제거하는 방법 (0) | 2022.09.21 |
유형을 지정하지 않고 Java Enum을 참조하려면 어떻게 해야 합니까? (0) | 2022.09.21 |
Gulp 태스크를 순차적으로 실행하는 방법 (0) | 2022.09.21 |