我处于一个小困境。我正在使用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()
cursor.execute("""SELECT serial FROM devices WHERE registered_id IS NOT NULL AND registered_id <>''""")
devices = cursor.fetchall()
print devices
except:
print "Something went wrong with the MySQL"
打印出来的时间如下:
(('00000000762c1d3c',),('000000003ad192f2',),('00000000ca91760d',), ( '000000004c9898aa',))
(我把它缩短了,因为它很长。)
如何将此列表正确解析为JSON,使其如下所示:
{"devices": ['00000000762c1d3c', '000000003ad192f2', '00000000ca91760d', '000000004c9898aa']}
感谢您的建议!
答案 0 :(得分:1)
data = {"devices": [item[0] for item in devices]}
json_data = json.dumps(data)