使用Flask 1.0.2on Windows,Python 3.6 64bit 首先我通过jquery ajax调用发送数据,这在 JS 端是有效的jsonvar 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: POSTis jsonb'"{ \\"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 回答
慕仙森
TA贡献1827条经验 获得超7个赞
JSON.stringify()接受一个 Javascript 对象并将其转换为 JSON 字符串。您不是向它传递一个对象,而是向它传递一个字符串,然后再次将其转换为 JSON。
由于请求数据包含双重编码的 JSON,因此该request.json属性会返回一个字符串而不是字典。
要修复,请更改:
var myData = '{ "id": "' +clickedID +'" }'
到:
var myData = { id: clickedID }
添加回答
举报
0/150
提交
取消