Python json.dumps(<val>) 输出缩小的 json? [英] Python json.dumps(<val>) to output minified json?

查看:83
本文介绍了Python json.dumps(<val>) 输出缩小的 json?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法让python的json.dumps(<val>)以缩小的形式输出?(即去掉逗号、冒号等周围的多余空格)

解决方案

你应该设置 separators 参数:

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

来自文档:

<块引用>

如果指定,分隔符应该是一个 (item_separator, key_separator) 元组.默认为 (', ', ': ') 如果缩进是 None(',', ': ') 否则.要获得最紧凑的 JSON 表示,您应该指定 (',', ':') 以消除空格.

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

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

Is there any way to have python's json.dumps(<val>) output in minified form? (i.e. get rid of extraneous spaces around commas, colons etc.)

解决方案

You should set the separators parameter:

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

From the docs:

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

这篇关于Python json.dumps(&lt;val&gt;) 输出缩小的 json?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆