【问题标题】:How can I return the "dict" in jsonify in Flask?如何在 Flask 的 jsonify 中返回“dict”?
【发布时间】:2021-12-26 06:26:44
【问题描述】:

这是我的代码:

@app.route('/students')
def students():
    list = Student.query.all()
    print(type(list)) #class:list


    studentList2 ={}

    for student in list:
        studentList2= ({'id':student.id,'title':student.title,'email':student.email})
        print(studentList2) # the loop can show student1,2,3 etc. 
    print(type(studentList2)) #class:dict

    print(studentList2) # Only show the last student

    return jsonify(studentList2)

循环可以显示student1,2,3等。但我不知道如何返回JSON。

【问题讨论】:

    标签: python for-loop sqlalchemy flask-restful


    【解决方案1】:

    我假设您想返回所有学生数据。您代码中的studentList2 不是dict,您需要删除()。 btw list是python中的关键字,所以不要覆盖它

    @app.route('/students')
    def students():
        lst = Student.query.all()
    
        studentList2 = []
    
        for student in lst:
            studentList2.append({'id':student.id,'title':student.title,'email':student.email})
        return jsonify(studentList2)
    

    【讨论】:

    • 谢谢,这就是我需要的答案!我已经花了几个小时找到解决方案!
    猜你喜欢
    • 2020-02-29
    • 2016-04-06
    • 2017-03-13
    • 2014-11-26
    • 2016-01-29
    • 1970-01-01
    • 1970-01-01
    • 2019-12-30
    • 1970-01-01
    相关资源
    最近更新 更多