我想在postman中使用json字符串数组将数据插入到mysql表中。 一个数据库中有两张表。一个用于提问,另一个用于回答。我想使用发布请求将问题和答案插入表中。
这里我尝试了一个代码。
app = Flask(__name__)
api = Api(app)
class train(Resource):
def post(self):
account_id = request.json['account_id']
question = request.json['question']
answer = request.json['answer']
question_id = request.json['question_id']
conn = db_connect.connect()
query =conn.execute ("INSERT INTO ai_question (account_id,question)
VALUES (%s, %s)", (account_id, question))
query1 =conn.execute ("INSERT INTO ai_answer (question_id, answer)
VALUES (%s,%s)", (question_id, answer))
result1 = {'data': [dict(zip(tuple (query.keys()) ,i)) for i in
query.cursor]}
result2 = {'data': [dict(zip(tuple (query1.keys()) ,i)) for i in
query1.cursor]}
return jsonify(result1, result2)
api.add_resource(trainings, '/trainings')
api.add_resource(ask, '/ask')
api.add_resource(train, '/train')
if __name__ == '__main__':
app.run('0.0.0.0',5000)
通过在 postman 中写入下面的 json 字符串来将数据插入表中。
{
"question":"abc",
"answer":"xyz",
"question_id":"1",
"account_id":"1"
}
但我想使用 postman 以这种方式插入数据:
{
"account_id":"11",
"data": [
{
"question":"how are you?",
"answer":"I am good how about you?"
},
{
"question":"thank you",
"answer":"welcome"
}
]
}
“问题”和“答案”是不同表中的列。
最佳答案
question = request.json['data'][0]['question']
会起作用的。
关于python - 将 json 字符串插入表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47936640/