正文

rapidjson与json有诸多不兼容,使用时需要注意。

两者输出的JSON格式有差异,json为了美观,在冒号和逗号之后默认加了空格。

rapidjson

snippet.python
[yz@test-4 yz]$ python3
>>> import rapidjson as json
>>> s = '{"x": "123", "y": "456"}'
>>> r = json.loads(s)
>>> j = json.dumps(r, indent=None, ensure_ascii=False)
>>> print(j)
{"x":"123","y":"456"}

json

snippet.python
[yz@test-4 yz]$ python3
>>> import json
>>> s = '{"x": "123", "y": "456"}'
>>> r = json.loads(s)
>>> j = json.dumps(r, indent=None, ensure_ascii=False)
>>> print(j)
{"x": "123", "y": "456"}

json可以使用separators控制是否加空格,但是,rapidjson没有这个参数。

snippet.python
[yz@test-4 yz]$ python3
>>> import json
>>> s = '{"x": "123", "y": "456"}'
>>> r = json.loads(s)
>>> j = json.dumps(r, indent=None, ensure_ascii=False)
>>> print(j)
{"x": "123", "y": "456"}
>>> j = json.dumps(r, indent=None, ensure_ascii=False, separators=(',',':'))
>>> print(j)
{"x":"123","y":"456"}
>>> j = json.dumps(r, indent=None, ensure_ascii=False, separators=(', ',': '))
>>> print(j)
{"x": "123", "y": "456"}

rapidjson.dumps没有separators参数:

snippet.python
[yz@test-4 yz]$ python3
>>> import rapidjson as json
>>> s = '{"x": "123", "y": "456"}'
>>> r = json.loads(s)
>>> j = json.dumps(r, indent=None, ensure_ascii=False, separators=(', ',': '))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'separators' is an invalid keyword argument for rapidjson.dumps()

参考