Python + JSON MD5 哈希的序列化 - 我如何保证两个等效对象将序列化为完全相同的字符串?

Python + JSON serialization for MD5 hash - how can I guarantee that two equivalent objects will serialize to exactly the same string?

我需要对 dict 或列表的内容进行 md5 散列,我想确保两个等效结构会给我相同的散列结果。

到目前为止,我的方法是仔细定义结构的顺序,并在 运行 到 json.dumps() 之前对它们包含的各种列表和词典进行排序。

然而,随着我的结构变得越来越复杂,这变得费力且容易出错,而且在任何情况下我都不确定它是否在 100% 的时间或仅在 98% 的时间内工作。

只是好奇是否有人对此有快速的解决方案?我可以在 json 模块中设置一个选项来完全排序对象吗?或者我可以使用其他一些技巧来对两个结构中的信息进行完整比较,return 保证其唯一的散列?

当我序列化对象时,我只需要字符串(然后是 md5)相同——我不关心这个用例的反序列化。

JSON 默认输出是不确定的,因为 __hash__ are salted for str (key values for typical JSON objects) to prevent a DoS vector (see the notes in documentation). For this reason you need to call json.dumps 的结果 sort_keys 设置为 True。

>>> import json
>>> d = {'this': 'This word', 'that': 'That other word', 'other': 'foo'}
>>> json.dumps(d)
'{"this": "This word", "other": "foo", "that": "That other word"}'
>>> json.dumps(d, sort_keys=True)
'{"other": "foo", "that": "That other word", "this": "This word"}'

对于最终序列化为 list 的对象(即 listtuple),您需要确保按预期方式进行排序,因为根据定义,列表是没有以任何特定方式排序(这些集合中元素的排序将保持在程序本身 placed/modified 的位置)。