将json字符串插入表中

时间:2017-12-22 06:10:10

标签: python mysql json flask 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'和'answer'是不同表格中的列。

1 个答案:

答案 0 :(得分:0)

question = request.json['data'][0]['question']

会奏效。