python 转JSON时 如何去除多余的空格

在Python中,我们使用json.dumps将 Python 对象编码成 JSON 字符串的时候,会出现很多空格。

因为有时候我们需要处理字符串,比如加密等,但是由于多了空格,加密后肯定不一致的,那么就需要去掉这些空格。

在json.dumps官方文档里也说明了,为了美观默认会加上逗号空格和冒号空格。

按照文档里说的,我们只需要加上separators=(',',':')这个参数就可以解决了。

 

官方文档:

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.

翻译:

如果指定,`separators``应该是一个``(项目分隔符,键分隔符)``

元组。默认值为“`(',',':')``如果*indent*为``None``并且

``(“,”,“:”)“否则。要获得最紧凑的JSON表示,

您应该指定“`(',',':')``以消除空白。

实验如下:

1
2
3
4
5
6
7
8
9
data = {
    "OperatorID": "MA63HLT72",
    "OperatorSecret": "328e03f235304778",
    "SigSecret": "d1ad80b40e8d48a5",
}
js = json.dumps(data)
print(js)
js = json.dumps(data, separators=(',', ':'))
print(js)

结果: 

1
2
{"OperatorID": "MA63HLT72", "OperatorSecret": "328e03f235304778", "SigSecret": "d1ad80b40e8d48a5"}
{"OperatorID":"MA63HLT72","OperatorSecret":"328e03f235304778","SigSecret":"d1ad80b40e8d48a5"}

 

参考:https://www.cnblogs.com/Hellowshuo/p/15706590.html

posted @   还是张先森  阅读(2272)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示