如何将我的 pymysql 查询结果转换为 json 格式?

How do I convert my pymysql query result to json format?

我正在制作一个 API,我需要 return json。

下面是我的views.py

from flask.json import jsonify
from team2_project import app
from team2_project import cursor
import json
from flask import jsonify
@app.route('/')
def index():
    sql = ("SELECT * FROM Clients_002")
    cursor.execute(sql)
    formulas = cursor.fetchall()

    return str(formulas)

init.py

from flask import Flask
import pymysql
pymysql.install_as_MySQLdb
import pymysql.cursors
app = Flask(__name__)
connection = pymysql.connect(host='',
                             user='',
                             password='',
                             db='',
                             cursorclass=pymysql.cursors.DictCursor)
cursor = connection.cursor(pymysql.cursors.DictCursor)

import team2_project.views

我的函数 returns:

[{"clientCompID_002": 1, "clientCompName_002": "Telus", "clientCity_002": "Halifax", "clientCompPassword_002": "002", "moneyOwed_002": "100"}, {"clientCompID_002": 2, "clientCompName_002": "Bell", "clientCity_002": "Dartmouth", "clientCompPassword_002": "002", "moneyOwed_002": "10"}, {"clientCompID_002": 3, "clientCompName_002": "Purple Cow", "clientCity_002": "Bedford", "clientCompPassword_002": "002", "moneyOwed_002": "120"}, {"clientCompID_002": 4, "clientCompName_002": "Apple", "clientCity_002": "Toronto", "clientCompPassword_002": "002", "moneyOwed_002": "1210"}, {"clientCompID_002": 5, "clientCompName_002": "Sowo", "clientCity_002": "Montreal", "clientCompPassword_002": "002", "moneyOwed_002": "1110"}]

如何在 json 中缩进输出?我尝试了 jsonify(),但它 return 的结果与 str() 相同。似乎无法摆脱方括号。

谢谢

使用json包的dumps()方法,它有一个你可以使用的缩进参数。

示例: json.dumps(formulas, indent=4)

如果您尝试fetchall(),将返回字典数组。要获得单个对象,您只需 fetchone()。所以,试试看,

formulas = cursor.fetchone()