格式化从MySQL中的MySQLdb到JSON的选择列表

时间:2017-01-07 23:22:21

标签: python json

我陷入了一个小困境。我使用Python的2.7版模块MySQLdb从表中获取列表。到目前为止,代码非常简单:

#!/usr/bin/python
import json
import MySQLdb

db_host = "localhost"
db_user = "xxx"
db_passwd = "yyy"
db_table = "table"

try:
        db = MySQLdb.connect(host=db_host, user=db_user, passwd=db_passwd, db=db_table)
        cursor = db.cursor(MySQLdb.cursors.DictCursor)
        cursor.execute("""SELECT serial, registered_id FROM devices WHERE registered_id IS NOT NULL AND registered_id <>''""")
        devices = cursor.fetchall()
        print devices
except:
        print "Something went wrong with the MySQL"

打印出来的时间如下:

  

((&#39; 00000000762c1d3c&#39;,&#39; 019&#39;),(&#39; 000000003ad192f2&#39;,   &#39; 045&#39;),(&#39; 000000004c9898aa&#39;,&#39; 027&#39;))

(我把它缩短了,因为它很长。)

如何将此列表正确解析为JSON,使其如下所示:

{
            "device":
                [
                    { "serial": "00000000762c1d3c", "registered_id": "019" },
                    { "serial": "000000003ad192f2", "registered_id": "045" },
                    { "serial": "000000004c9898aa", "registered_id": "027" },
                ]
        }

我已经想通过将此与DictCursors相对应来添加:

for row in devices:
        print "%s, %s" % (row["serial"], row["registered_id"])

我能够分别打印它们。但我仍然无法弄清楚如何正确构建JSON。

感谢您的建议!

1 个答案:

答案 0 :(得分:1)

DictCursor可能会使事情变得更简单:

import json

db = MySQLdb.connect(host=db_host, 
                     user=db_user, 
                     passwd=db_passwd, 
                     db=db_table, 
                     cursorclass=MySQLdb.cursors.DictCursor)
cursor = db.cursor()
cursor.execute("""SELECT serial, registered_id FROM devices WHERE registered_id IS NOT NULL AND registered_id <>''""")
devices = cursor.fetchall()

data = {"device": list(devices)}

# dump to a json file
with open("output.json", "w") as f:
    json.dump(data, f)