python - 将 json 字符串插入表中

标签 python mysql json flask postman

我想在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/

相关文章:

python - 如何正确记录查询参数(搜索,过滤)Django Rest Framework?

python - 具有默认值的类属性和实例变量之间的区别

Python 正则表达式匹配搜索字符串的意外部分

python - 使用 if-else 创建新列时 Pandas 出错 : The truth value of a Series is ambiguous

php - 在服务器上加载图像时出错

json - 将 JSON 对象转换为 RDD

php - 一个数据库。一个领域。一个 html 动态表。无法提取有限数量的数据

mysql - 为 2 个表选择同一列

JavaScript - "Filter"通过对象 - 最佳实践?

ios - JSON解析swift,数组在NSURLSession之外没有值