我正在python flask中创建api。我正在将MySQL用于数据库,并使用SELECT查询成功获取了数据。我已经使用flask的jsonify以json格式返回了数据。我想问的是,在使用整数作为索引的jsonify之后,我正在以以下格式获取json
int main()
{
cv::Mat image1, flat_image;
cv::Mat initial_image = cv::imread("D:\mémoire\DB\to use in training\images_sorted\\image1.jpg", 0);
cv::Mat trainData = initial_image.reshape(1, 1);
////// trainData
for (int i = 2; i < 30; i++)
{
std::string filename = "D:\mémoire\DB\to use in training\images_sorted\\image";
filename = filename + std::to_string(i);
filename = filename + ".jpg";
image1 = cv::imread(filename, 0);
flat_image = image1.reshape(1, 1);
trainData.push_back(flat_image);
}
}
这很好,我可以使用它,但是我正在寻找具有数据库表属性作为其索引的json,就像我们可以在nodejs中获取那样,因此在字体结尾工作将更加容易。我想使用以下格式的json,其中index是我的数据库表列名称。
[
[
1,
"FURNITURE",
"INDOOR FURNITURE"
],
[
2,
"AUTOMOBILES",
"CARS, BIKES"
],
[
3,
"LAPTOP & ACCESSORIES",
"LAPTOP, MOUSE, KEY BOARD, PENDRIVE"
]
]
答案 0 :(得分:1)
该问题未指定您的SQL适配器,但是如果您将SQLAlchemy与Flask一起使用,则以下是如何查询数据库并以所需格式输出结果的示例:
from flask import Flask
from models import db
import json
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'your_database_connection_string'
db.init_app(app)
result = db.session.execute("SELECT * FROM categories WHERE id = :id", {"id":999})
# If no rows were returned (e.g., an UPDATE or DELETE), return an empty list
if result.returns_rows == False:
response = []
# Convert the response to a plain list of dicts
else:
response = [dict(row.items()) for row in result]
# Output the query result as JSON
print(json.dumps(response))
答案 1 :(得分:1)
我找到了使用sql-alchemy更好的解决方案。如果仍然需要按照问题陈述的解决方案,那么这里是一个解决方案
import json
def conv_func(list_data):
dic ={ "CATEGORY_ID":list_data[0],
"CATEGORY_NAME":list_data[1],
"DESCRIPTION":list_data[2]
}
return dic
data = '''[[
1,
"FURNITURE",
"INDOOR FURNITURE"
],
[
2,
"AUTOMOBILES",
"CARS, BIKES"
],
[
3,
"LAPTOP & ACCESSORIES",
"LAPTOP, MOUSE, KEY BOARD, PENDRIVE"
]
]'''
data = json.loads(data)
new_data=[]
for i in data:
new_data.append(conv_func(i))
print(new_data)
答案 2 :(得分:1)
import pymysql
cur = mysql.connect().cursor(pymysql.cursors.DictCursor)
cur.execute(sql)
row = cur.fetchall()
print row
[{u'symbol': u'AAPL'}, {u'symbol': u'SQ'}]