【发布时间】:2019-01-17 01:12:07
【问题描述】:
我需要在 Python 3 中生成一个 MD5 哈希来与在 Python 2 上生成的 MD5 哈希进行比较,但是 json.dumps() 的结果是不同的,因为在 Python 2 上元素的位置发生了变化并且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())
Python 2.7 结果:
('CONTENT:', {'interests': [{'id': 1, 'description': 'tecnology'}], 'age': 30, 'name': 'Marcelo', 'address': {'country': 'Brasil'}})
('MD5:', 'a396f6997fb420992d96b37e8f37938d')
Python 3.6 结果:
CONTENT: {'name': 'Marcelo', 'age': 30, 'address': {'country': 'Brasil'}, 'interests': [{'id': 1, 'description': 'tecnology'}]}
MD5: 40c601152725654148811749d9fc8878
编辑:
我无法更改在 Python 2 上生成的 MD5。有什么方法可以在 Python 3 上重现 Python 2 的默认顺序?
【问题讨论】:
-
字典没有排序,因此即使对于相同的 Python 版本也不能保证准确的 json 输出。
标签: python json python-2.7 md5 python-3.6