python json 转换问题
前两天我负责的支付系统和合作的商户进行接口对接,又遇到一个不同语言 PHP 和 Python 参数转换为 json 问题导致签名校验不通过。我们生成签名的规则请求参数转成 json + token + 特殊字符和时间戳。
PHP 数组转 json 函数为 json_encode() 输出格式如下:
$data = [
'mch_id' => 1,
'app_id' => 1001
];
echo json_encode($data);
// 输出 {"mch_id":1,"app_id":1001}
Python json 标准库中有 json.dumps() 方法输出格式如下:
data = {'mch_id':1,'app_id':1001}
print(json.dumps(data))
//输出 {"mch_id": 1, "app_id": 1001}
不仔细看是很难发现差异的,Python 转换之后得到的数据 key: value 之间默认是有空格的。
查看 json.dumps() 源码之后发现里面有这么一段注释
If
indentis a non-negative integer, then JSON array elements and
object members will be pretty-printed with that indent level. An indent
level of 0 will only insert newlines.Noneis the most compact
representation. Since the default item separator is', ', the
output might include trailing whitespace whenindentis specified.
You can useseparators=(',', ': ')to avoid this.If
separatorsis an(item_separator, dict_separator)tuple
then it will be used instead of the default(', ', ': ')separators.
(',', ':')is the most compact JSON representation.
大概意思是默认转换为 json 之后每一对 key 和 value 之间会有空格。如果要紧凑型可以添加分隔符给第二个参数。其实在网上搜索也能找到解决方法,但是看源码比较靠谱一些。
最终代码为:
data = {'mch_id':1,'app_id':1001}
print(json.dumps(data, separators=(',',':')))
//输出 {"mch_id":1,"app_id":1001}
之前我还写了一篇 PHP 和 JAVA 也是 json 转换问题导致对比签名失败,感兴趣可以看一下。https://wp.hellocode.name/?p=1148


您将是第一位评论人!