为什么 json.dumps() in python 3 return 是 python 2 的不同值?

Why json.dumps() in python 3 return a different value of python 2?

我需要在 Python 3 中生成一个 MD5 哈希来与在 Python 2 中生成的 MD5 哈希进行比较,但是 json.dumps() 的结果不同,因为在Python2上元素的位置发生变化,MD5结果不同。

如何生成相同的结果?

代码:

content = {'name': 'Marcelo', 'age': 30, 'address': {'country': 'Brasil'}, 'interests': [{'id': 1, 'description': 'tecnology'}]}

print('CONTENT:', json.dumps(content))

print('MD5:', md5(str(content).encode('UTF-8')).hexdigest())

Python2.7 结果:

('CONTENT:', {'interests': [{'id': 1, 'description': 'tecnology'}], 'age': 30, 'name': 'Marcelo', 'address': {'country': 'Brasil'}})

('MD5:', 'a396f6997fb420992d96b37e8f37938d')

Python3.6结果:

CONTENT: {'name': 'Marcelo', 'age': 30, 'address': {'country': 'Brasil'}, 'interests': [{'id': 1, 'description': 'tecnology'}]}

MD5: 40c601152725654148811749d9fc8878

编辑:

我无法更改 Python 生成的 MD5 2. 有什么方法可以在 Python 3 上重现 Python 2 的默认顺序?

在3.6之前的Python中,字典键没有排序。所以在 Python 3.6 中,键保持它们插入的顺序(或者在字典文字的情况下,它们在文字中的出现方式)。 Python 2.7 字典是无序的,所以循环顺序不一定匹配插入顺序。

如果您在这两种情况下都重新加载 json 字典,它仍然是相等的(字典相等不取决于顺序)。

所以这里没有错误。不同之处在于词典在不同 Python 版本中的排序方式。

json.dumpjson.dumps 以字典循环顺序写出键值对。所以为了有一致的循环顺序,最好使用 collections.OrderedDict 类型来实现一致的顺序。如果您调用 json.load 来获取词典,您还需要使用 json.loads(text, object_hook=OrderedDict),这将保持顺序。

没有简单的方法可以使 Python 3 字典使用 Python 2 排序,因此将 2 和 3 代码库都移动到使用 OrderedDict 是一个更易于维护的解决方案。