Python json.dumps(<val>)以输出缩小的json?

2024-05-16 05:02:42 发布

您现在位置:Python中文网/ 问答频道 /正文

有什么方法可以将python的json.dumps(<val>)输出为小型形式吗?(即去掉逗号、冒号等周围的多余空格)


Tags: 方法jsonval形式空格逗号dumps冒号
2条回答

您应该设置separators参数:

>>> json.dumps([1, 2, 3, {'4': 5, '6': 7}], separators=(',', ':'))
'[1,2,3,{"4":5,"6":7}]'

从文档中:

If specified, separators should be an (item_separator, key_separator) tuple. The default is (', ', ': ') if indent is None and (',', ': ') otherwise. To get the most compact JSON representation, you should specify (',', ':') to eliminate whitespace.

https://docs.python.org/3/library/json.html

https://docs.python.org/2/library/json.html

还有一个ujson库,它的工作速度更快,默认情况下会缩小JSON。
它的dumps等价物没有separators参数,并且它缺少一些其他特性,比如自定义编码器/解码器,但是我认为这里值得一提。

>>> ujson.dumps([1,2,3,{'4': 5, '6': 7}])
'[1,2,3,{"4":5,"6":7}]'

相关问题 更多 >