2016-07-28 60 views
0

不知道json的结构,我该如何从数据库查询返回一个json对象?所有的信息都在那里,我无法弄清楚如何构建这个对象。从sql数据库光标构建json数据

import MySQLdb 
import json 
db = MySQLdb.connect(host, user, password, db) 
cursor = db.cursor() 
cursor.execute(query) 
rows = cursor.fetchall() 

field_names = [i[0] for i in cursor.description] 
json_string = json.dumps(dict(rows)) 

print field_names[0] 
print field_names[1] 
print json_string 

db.close() 

计数

严重性

{ “321”: “7.2”, “1”: “5.0”, “5”: “4.3”, “7”:“6.8 ”, “1447”: “9.3”, “176”: “10.0”}

JSON对象看起来像:

{"data":[{"count":"321","severity":"7.2"},{"count":"1","severity":"5.0"},{"count":"5","severity":"4.3"},{"count":"7","severity":"6.8"},{"count":"1447","severity":"9.3"},{"count":"176","severity":"10.0"}]} 

回答

1

您遇到的问题的发生是因为您只将取出的项目转换为字符串,没有它们的描述。

dict在python期望另一个字典或一个迭代返回两个项目的元组,其中每个元组的第一个项目将是关键,第二个值。

由于您只获取两列,因此您将第一个(count)作为关键字,将第二个(严重性)作为每个获取行的值。

你想要做的是还结合的描述,像这样什么:

json_string = json.dumps([ 
{description: value for description, value in zip(field_names, row)} 
for row in rows]) 
1

1 - 您可以使用pymsqlDictCursor

import pymysql 
connection = pymysql.connect(db="test") 
cursor = connection.cursor(pymysql.cursors.DictCursor) 
cursor.execute("SELECT ...") 
row = cursor.fetchone() 
print row["key"] 

2- MySQLdb的还包括DictCursor,您可以使用。进行连接时,您需要通过cursorclass=MySQLdb.cursors.DictCursor

import MySQLdb 
import MySQLdb.cursors 
connection = MySQLdb.connect(db="test",cursorclass=MySQLdb.cursors.DictCursor) 
cursor = connection.cursor() 
cursor.execute("SELECT ...") 
row = cursor.fetchone() 
print row["key"] 
0

我得到这个使用集合库的工作,虽然代码是混乱:

import MySQLdb 
import json 
import collections 
db = MySQLdb.connect(host, user, passwd, db) 
cursor = db.cursor() 
cursor.execute(query) 
rows = cursor.fetchall() 
field_names = [i[0] for i in cursor.description] 

objects_list = [] 
for row in rows: 
    d = collections.OrderedDict() 
    d[ field_names[0] ] = row[0] 
    d[ field_names[1] ] = row[1] 
    objects_list.append(d) 

json_string = json.dumps(objects_list) 

print json_string 

db.close() 

[ {“count”:176,“severity”:“10.0”},{“count”:1447,“severity”:“9.3”},{“count”:321,“severity”:“7.2”},{“ count“:7,”severity“:”6.8“},{”count“:1,”severity“:”5.8“},{”count“:1,”severity“:”5.0“},{”count“ :5,“严重性”:“4.3”}]