【发布时间】:2022-01-18 14:35:17
【问题描述】:
我有一个基于类的视图,其中有一个 put 函数并试图将 request.body 放入 json。
from django.views import View
import json
class StudentView(View):
def put(self, request):
body = request.body #b'name=Arpita+kumari+Verma&roll=109&city=USA'
json_body = json.loads(body) # JSONError 'expecting dict values but given bytes object'
# I want something like this
# {
# 'name':'Arpita kumari Verma',
# 'roll':109,
# 'city':'USA',
# }
json_dumped_data = json.dumps(json_body)
return HttpResponse(json_dumped_data, content_type="application/json")
我的请求应用
url = 'http://127.0.0.1:8000/api/student/'
json_data = {
'name':'Arpita kumari Verma',
'roll':109,
'city':'USA'
}
results = requests.put(url, json_data)
【问题讨论】:
-
用
json.loads(body.decode())替换json.loads(body) -
raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
-
查看你的http请求,当http body为
None时,可以加try except处理。 -
好的,我发现
#b'name=Arpita+kumari+Verma&roll=109&city=USA'根本不是json字符串,你能提供你的http url和body吗? -
在这里我为你添加了我的请求应用程序,但是我能够以字节格式获取 request.body,所以它不是
none。
标签: django django-rest-framework django-serializer