【发布时间】:2016-08-02 14:00:22
【问题描述】:
如果您向下滚动一点,您可以从 g.d.d.c return SQL table as JSON in python 看到此代码:
qry = "Select Id, Name, Artist, Album From MP3s Order By Name, Artist"
# Assumes conn is a database connection.
cursor = conn.cursor()
cursor.execute(qry)
rows = [x for x in cursor]
cols = [x[0] for x in cursor.description]
songs = []
for row in rows:
song = {}
for prop, val in zip(cols, row):
song[prop] = val
songs.append(song)
# Create a string representation of your array of songs.
songsJSON = json.dumps(songs)
我只想保持列的顺序。
例如当我print(cols) 我得到这个:
['id', 'Color', 'YCoord', 'Width', 'Height'] # right order
但列的保存顺序错误:
[{"Color": "#FF99FF","Width"=345, "id"=43, "YCoord"=5784 "Height"=-546}...] # wrong order
我添加的列越多,它就越随机。
【问题讨论】:
-
字典未排序,请将
song = {}替换为song = OrderedDict()。您需要在脚本顶部from collections import OrderedDict -
这对我来说既快捷又简单。非常感谢!
标签: python sql-server json pyodbc