最好是采用 OrderedDict + json.dumps方案

1. 在存储 content 的时候就使用 OrderedDict 而非用默认的 dict

from collections import OrderedDict
content = OrderedDict();
content['id'] = "evt_ugB6x3K43D16wXCcqbplWAJo"
.....
content['created'] = 1440407501
jcont = json.dump(content); 
# {"id":"evt_ugB6x3K43D16wXCcqbplWAJo","created":1440407501}
# type(jcont) #<type 'str'>

这样得出的最终的 dict 从头到尾都是有序的, OrderedDict 其实可以看做是 dict 的一个子类,强行保留了其字典序,但是这样消耗的资源要更多。

2. 如果要重新转化为 json 格式但是仍要保证其已有顺序需要在 json.loads() 中使用参数 object_pairs_hook

jod = json.loads(jcont, object_pairs_hook=OrderedDict);
type(jod) # <type collections.OrderedDict>

这样才是一个完整的保证出入有序的方案。

相关文章:

  • 2021-10-22
  • 2022-12-23
  • 2022-01-24
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-05-19
  • 2021-04-28
  • 2021-12-27
相关资源
相似解决方案