Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/55.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Python从MySQL获取JSON格式的列表_Python_Mysql_Json - Fatal编程技术网

使用Python从MySQL获取JSON格式的列表

使用Python从MySQL获取JSON格式的列表,python,mysql,json,Python,Mysql,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,

我有点进退两难。我正在使用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"

谢谢你的建议

注意:只有多行字符串才需要三重引号字符串
“…”
,否则只需添加不必要的杂波即可。
data = {"devices": [item[0] for item in devices]}
json_data = json.dumps(data)
data = {"devices": [item[0] for item in devices]}
json_data = json.dumps(data)