使用 python 将 MySQL 输出为 JSON

标签 mysql json python-3.x

我试图从 Flask API 获取这样的 JSON 输出,该 API 从 MySQL 数据库获取数据。

[{
  'date': '2016-01-01',
  'total': 17164,
  'details': [{
    'name': 'Project 1',
    'date': '2016-01-01 12:30:45',
    'value': 9192
  }, {
    'name': 'Project 2',
    'date': '2016-01-01 13:37:00',
    'value': 6753
  },
  {
    'name': 'Project N',
    'date': '2016-01-01 17:52:41',
    'value': 1219
  }]
}]

API定义如下:

@app.route('/api/getSalesHeatData', methods=['GET'])
@cross_origin() # allow all origins all methods.
def get_Sales_Heat_Data():
db = getMysqlConnection()
print(db)
try:
    sqlstr1 = "SELECT InvoiceDateOnly, sum(Quantity) from testing group by InvoiceDateOnly"
    print(sqlstr1)
    sqlstr2 = "SELECT InvoiceDateOnly, Description, Quantity from testing"
    print(sqlstr2)
    cur1 = db.cursor()
    cur1.execute(sqlstr1)
    output_json1 = cur1.fetchall()
    cur2 = db.cursor()
    cur2.execute(sqlstr2)
    output_json2 = cur2.fetchall()
    user_list = []
    for row1 in output_json1:
        d = collections.OrderedDict()
        d['date']  = str(row1[0])
        d['total']   = row1[1]
        for row2 in output_json2:
           if row1[0] == row2[0]:
               f = collections.OrderedDict()
               f['desc']   = row2[1]
               f['date']   = str(row2[0])
               f['qty']   = row2[2]
               d.append(f)
        user_list.append(d)
except Exception as e:
    print("Error in SQL:\n", e)
finally:
    db.close()
return json.dumps(user_list)`

输出在终端中返回错误,但显示状态 200,但没有数据。请就此向我提出建议。我是 python 新手,如果这是一个愚蠢的错误,请原谅我。

最佳答案

我找到了问题的答案。我将 d.append(f) 更改为 d['details'] = f

关于使用 python 将 MySQL 输出为 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45294562/

相关文章:

java.sql.Types.JSON 不是默认的 JDBC 类型

mysql - 在 RPI/优化查询上运行 MySQL

mysql - 在mysql中导入一个txt文件

javascript - 从 JSON 对象中减去数组 JavaScript

python - 创建一个包含 0,1,0.5 值的列,而不是 pandas 中的 bool 值

python3 vlc模块 - 没有音频

python - 如果您从不重新定义任何内置函数,为什么还要导入内置函数?

mysql - 如何构建附加列等于关联行数的 MySQL 查询?

php - 防止向数据库中添加数据

javascript - 使用 getJSON 从服务器调用带有变音符号的 JSON 文本文件