为什么python 3中的json.dumps()返回python 2的不同值? [英] Why json.dumps() in python 3 return a different value of python 2?

查看:702
本文介绍了为什么python 3中的json.dumps()返回python 2的不同值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to generate a MD5 Hash in Python 3 to compare with a MD5 Hash that was generated on Python 2, but the result for json.dumps() is different, because on Python 2 the position of the elements changes and the MD5 result is different.

如何产生相同的结果?

代码:

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的默认顺序?

推荐答案

在3.6之前的Python中,字典键不排序.因此,在Python 3.6中,键保持其插入顺序(或在字典文字的情况下,它们在文字中的显示方式). Python 2.7字典是无序的,因此循环顺序不一定与插入顺序匹配.

In Python before 3.6, the dictionary keys are not ordered. So in Python 3.6, the keys maintain the order of their insertion (or in the case of a dictionary literal, how they appear in the literal). The Python 2.7 dictionary is unordered, so the looping order does not necessarily match insertion order.

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

If you were to reload the json dictionary in both cases, it would still be equal (dictionary equality does not depend on order).

因此,这里没有错误.差异是因为在不同的Python版本中字典的排序方式.

So there is no error here. The difference is because of how dictionaries are ordered in different Python versions.

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

json.dump and json.dumps write the key-value pairs out in the dictionary looping order. So in order to have consistent looping order, it would be best to use the collections.OrderedDict type in order to achieve consistent ordering. If you are calling json.load to get dictionaries, you would also need to use json.loads(text, object_hook=OrderedDict), which will then maintain ordering.

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

There is no trivial way to make Python 3 dictionaries use a Python 2 ordering, so moving both 2 and 3 code bases to use OrderedDict is a more maintainable solution.

这篇关于为什么python 3中的json.dumps()返回python 2的不同值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆