猿问

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

使用Flask 1.0.2on Windows,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'


慕侠2389804
浏览 1247回答 2
2回答

慕仙森

JSON.stringify()接受一个 Javascript 对象并将其转换为 JSON 字符串。您不是向它传递一个对象,而是向它传递一个字符串,然后再次将其转换为 JSON。由于请求数据包含双重编码的 JSON,因此该request.json属性会返回一个字符串而不是字典。要修复,请更改:var myData = '{ "id": "' +clickedID +'" }'到:var myData = { id: clickedID }
随时随地看视频慕课网APP

相关分类

Python
我要回答