Flask request.get_json()返回字符串而不是json

时间:2018-12-01 10:20:22

标签: python json flask

Flask 1.0.2Windows上使用Python 3.6 64bit 首先,我通过jquery ajax调用发送数据,该调用在JS端有效json

var myData = '{ "id": "' +clickedID +'" }'
$.ajax({
    type: "POST", // HTTP method POST or GET
    contentType: 'application/json; charset=utf-8', //content type
    url: $SCRIPT_ROOT + '/colors/delete', //Where to make Ajax calls
    dataType:'json', // Data type, HTML, json etc.
    processData: false,
    data:JSON.stringify(myData), 
});

在烧瓶中,我捕获了POST请求并尝试解析它:

if request.method == "POST":
    print("got request method POST")
if request.is_json:
    print("is json")
    data_json = request.get_json(force=True)
    data_req = request.data
    print("{} is {}".format(data_req, type(data_req)))
    print("{} is {}".format(data_json, type(data_json)))
    data_json2 = json.loads(request.get_json(silent=True, force=True))
    print("{} is {}".format(data_json2, type(data_json2)))
    print (request.json.keys())

结果:

got request: POST
is json
b'"{ \\"id\\": \\"1\\" }"' is <class 'bytes'>
{ "id": "1" } is <class 'str'>
{'id': '1'} is <class 'dict'>
print (request.json.keys())
AttributeError: 'str' object has no attribute 'keys'

2 个答案:

答案 0 :(得分:1)

request.json接受一个Javascript对象并将其转换为JSON字符串。您没有向其传递对象,而是向其传递了JSON字符串,然后该字符串又再次转换为JSON。

因为请求数据包含双重编码的JSON,所以var myData = '{ "id": "' +clickedID +'" }' 属性为您提供了一个字符串而不是字典。

要修复,请更改:

var myData = { id: clickedID }

收件人:

if(position==list.Size()-1){
   divider.setVisibility(View.Gone)
}else{
   divider.setVisibility(View.Visible)
}

答案 1 :(得分:0)

在概述中,您将对象序列化为JSON(实际上是字符串),使用JSON数据类型将其发布,然后反序列化以将该对象取回。一些对象易于使用现成的功能进行序列化和反序列化。请参阅下面基于您的代码修改的示例(忽略CORS,这是由于我设置了测试环境)。

import logging, json
from flask import Flask, request, jsonify
from flask_cors import CORS
app = Flask(__name__)
CORS(app)

@app.route("/api",methods=['POST'])
def hello():
    logging.info('hello')
    if request.method == "POST":
        print("got request method POST")
    if request.is_json:
        print("is json")
        data = request.get_json()
        print("type of data {}".format(type(data))) # type dict
        print("data as string {}".format(json.dumps(data)))
        print ("keys {}".format(json.dumps(data.keys())))
    return jsonify(message='success')

if __name__ == "__main__":
    app.run()

<html>
    <style>
    </style>
    <button onClick="_ajax()">POST</button>
    <script src="jquery.js"></script>
    <script>
        const url_path = "http://localhost:5000/api";
        function _ajax() {
            console.log('_ajax called');
            var xhttp = new XMLHttpRequest();
            var clickedID="testClickedID";
            var myData = {"id": clickedID};
            $.ajax({
                type: "POST", // HTTP method POST or GET
                contentType: 'application/json; charset=utf-8', //content type
                url: url_path, //Where to make Ajax calls
                dataType:'json', // Data type, HTML, json etc.
                processData: false,
                data: JSON.stringify(myData), 
            }).done(
                function(data) {
                    console.log(data);
                }
            );
        }
    </script>
</html>