众所周知:python json 可以转换的json字符串,但是在将其转换为字典时,出现了乱序

字典是一个散列结构,亦即他自身根据key进行排序,无法保证顺序

import json

jsonstr = '{"username":"string","age":"int","income":"float","createdTime":"date"}'

print(json.loads(jsonstr))

输出结果不一致

代码打印  {'age': 'int', 'createdTime': 'date', 'username': 'string', 'income': 'float'}

控制台:

>>> import json
>>> jsonstr =  '{"username":"string","age":"int","income":"float","createdTime":"date"}'
>>> print(json.loads(jsonstr))
{'username': 'string', 'age': 'int', 'income': 'float', 'createdTime': 'date'}
>>>

 

 

 

最后采用有序字典集合:collections.OrderedDict ,二者输出保持一致

dictStr = json.loads(jsonstr,object_pairs_hook=collections.OrderedDict)

 

Logo

AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。

更多推荐