django 接受post请求json.dumps()的时候会引发TypeError: 'expected string or buffer'错误

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zyy247796143/article/details/71023086
在客户端中json.dumps() 一个{'a': 1,'b':2}的字典 ,post请求发送到django中。
在django的request.POST得到的是django.http.request.QueryDict对象,而不是json串,使用json.dumps()的时候会引发TypeError: 'expected string or buffer'错误。

因此,可以使用myDict = dict(queryDict.iterlists())转换为字典形式,不用json.dumps()进行转换

代码例子如下:

views.py

from django.shortcuts import render_to_response

def recv_data(request):
    recvdata = {}
    if request.method == "POST" and request.POST:
        recvdata = request.POST
        print recvdata
        print type(recvdata)
        print '-----------------------------'
        data = dict(recvdata.iterlists())
        data = eval(data.keys()[0].encode())
        print data
        print type(data)

    return render_to_response('recvdata.html',locals())

print看到的代码如下:

<QueryDict: {u'{"a": 1, "b": 2}': [u'']}>
<class 'django.http.request.QueryDict'>
-----------------------------
{'a': 1, 'b': 2}
<type 'dict'>

猜你喜欢

转载自blog.csdn.net/zyy247796143/article/details/71023086