不知道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"}]}