Python 解码Django POST请求正文

Python 解码Django POST请求正文,python,jquery,json,django,post,Python,Jquery,Json,Django,Post,我正在使用cordova构建一个映射应用程序,并发出post请求,发送以下JSON(特性) } 这是发送请求的JQuery代码 function savePub(feature){ $.ajax({ type: "POST", headers: {"csrfmiddlewaretoken": csrftoken}, url: HOST + URLS["savePub"], data: { pub_feature: JSON.stringify(f

我正在使用cordova构建一个映射应用程序,并发出post请求,发送以下JSON(特性)

}

这是发送请求的JQuery代码

function savePub(feature){

$.ajax({
    type: "POST",
    headers: {"csrfmiddlewaretoken": csrftoken},
    url: HOST + URLS["savePub"],
    data: {
        pub_feature: JSON.stringify(feature)
    },
    contentType:"application/json; charset=utf-8"
}).done(function (data, status, xhr) {
    console.log(data + " " + status);
    pubDialogAlert("Pub saved",feature);
}).fail(function (xhr, status, error) {
    showOkAlert(error);
    console.log(status + " " + error);
    console.log(xhr);
}).always(function () {
    $.mobile.navigate("#map-page");
});
}

当Django后端接收到请求时,我不确定为什么在打印请求正文时会出现这样的情况

b'pub_feature=%22%7B%5C%22type%5C%22%3A%5C%22Feature%5C%22%2C%5C%22geometry%5C%22%3A%7B%5C%22type%5C%22%3A%5C%22Point%5C%22%2C%5C%22coordinates%5C%22%3A%5B-6.6865857%2C53.2906136%5D%7D%2C%5C%22properties%5C%22%3A%7B%5C%22amenity%5C%22%3A%5C%22pub%5C%22%2C%5C%22name%5C%22%3A%5C%22The+Parade+Ring%5C%22%7D%7D%22'
当我尝试解码它,然后使用json.loads()时,它会抛出这个错误

@api_view(['POST'])
def save_pub(request):
if request.method == "POST":

    data = request.body.decode('utf-8')
    received_json_data = json.loads(data)

    return Response(str(received_json_data) + " written to db", status=status.HTTP_200_OK)


JSONDecodeError at /savepub/
Expecting value: line 1 column 1 (char 0)
我之所以这样假设,是因为一旦它解码了二进制字符串,就无法将其转换为有效的JSON,因为这些字符是%22等,但我不知道解决方案是什么

任何帮助都将不胜感激。
谢谢

您在这里混淆了两件事,表单编码和JSON格式。您拥有的是一个带有一个键的表单编码post,
pub_feature
,其值是一个JSON对象

相反,您应该直接发布JSON:

data: JSON.stringify(feature),

然后你就可以像以前一样加载它了——不过请注意,你真的应该让DRF帮你处理这个问题

我认为你只需要删除
pub_feature=
,然后
url=urllib.unquote(request.body.decode('utf-8'))
谢谢。将POST更改为data:JSON.stringify(功能)并使用Django Rest框架是有效的。。
data: JSON.stringify(feature),