向JSON倾销字典时维持秩序 [英] Maintain order when dumping dict to JSON

查看:149
本文介绍了向JSON倾销字典时维持秩序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将数据库查询的结果序列化为JSON。每行都有一些列,我添加到字典。列是按照一定的顺序,但是当我序列化数据的顺序改变。我尝试使用 OrderedDict ,但仍然看到相同的问题。如何维护列的顺序?

  res = {'a':i [0],'b': i [1],'c':i [2]} 
返回jsonify(res = res)




$ b $

  res = OrderedDict()
res ['a'] = i [0]
res ['b' ] = i [1]
res ['c'] = i [3]
返回jsonify(res = res)


解决方案

Python的字典和JSON对象没有顺序,所以没有直接的方法来做到这一点。在Python中, OrderedDict 维护插入顺序,但是在JSON中没有等价物。您可以将字典转换为其项目列表,因为列表已订购。

  data = OrderedDict()
data ['a'] = 1
data ['b'] = 2
jsonify(data = list(data.items()))
pre>

如果您需要知道这个特定的列表实际上是一个有序的字典,您可以使用标记方案来标记每个值的类型。这变得相当复杂。您可以在 Flask的会话序列化程序


I want to serialize the results of a database query to JSON. Each row has a number of columns, with I add to a dict. The columns are in a certain order, but when I serialize the data the order changes. I tried using an OrderedDict, but still saw the same issue. How can I maintain the order of the columns?

res = {'a': i[0], 'b': i[1], 'c': i[2]}
return jsonify(res=res)

res = OrderedDict()
res['a'] = i[0]
res['b'] = i[1]
res['c'] = i[3]
return jsonify(res=res)

解决方案

Python dicts and JSON objects have no order, so there is no direct way to do this. In Python, OrderedDict maintains the insert order, but there is no equivalent in JSON. You can convert the dict to a list of its items, since lists are ordered.

data = OrderedDict()
data['a'] = 1
data['b'] = 2
jsonify(data=list(data.items()))

If you need to know that this particular list is actually an ordered dict, you can use a tagging scheme to tag the type of each value. This gets considerably more complicated. You can find an example of it in Flask's session serializer.

这篇关于向JSON倾销字典时维持秩序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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