向JSON倾销字典时维持秩序 [英] Maintain order when dumping dict to 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()
pre>
data ['a'] = 1
data ['b'] = 2
jsonify(data = list(data.items()))
如果您需要知道这个特定的列表实际上是一个有序的字典,您可以使用标记方案来标记每个值的类型。这变得相当复杂。您可以在 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屋!