For some reason I cannot figure out why Django isn't handling my request.body content correctly.

It is being sent in JSON format, and looking at the Network tab in Dev Tools shows this as the request payload:

{creator: "creatorname", content: "postcontent", date: "04/21/2015"}

which is exactly how I want it to be sent to my API.

In Django I have a view that accepts this request as a parameter and just for my testing purposes, should print request.body["content"] to the console.

Of course, nothing is being printed out, but when I print request.body I get this:

b'{"creator":"creatorname","content":"postcontent","date":"04/21/2015"}'

so I know that I do have a body being sent.

I've tried using json = json.loads(request.body) to no avail either. Printing json after setting that variable also returns nothing.

推荐答案

In Python 3.0 to Python 3.5.x, json.loads() will only accept a unicode string, so you must decode request.body (which is a byte string) before passing it to json.loads().

body_unicode = request.body.decode('utf-8')
body = json.loads(body_unicode)
content = body['content']

In Python 3.6, json.loads() accepts bytes or bytearrays. Therefore you shouldn't need to decode request.body (assuming it's encoded in UTF-8, UTF-16 or UTF-32).

Json相关问答推荐

您可以使用Jolt对JSON执行OR条件吗

使用单元和非单元版本反序列化Rust中的枚举,而无需编写自定义反序列化程序

Postgres Select json数组并重新映射属性名称

(已回答)JSON 读取函数返回未定义而不是预期值 - Typescript

使用 Jolt 变换将平面 json 转换为具有多个数组的嵌套 Json

使用 System.Text.Json 序列化记录成员

错误字符串的长度超过了maxJsonLength属性设置的值

如何判断 Json 对象中是否存在键并获取其值

为什么在我们有 json_encode 时使用 CJSON 编码

从多维数组数据生成json字符串

jquery用json数据填充下拉列表

在 Rails 3 中处理 JS/ERB 模板中的 JSON

如何向从文件中检索的 JSON 数据添加键值?

在自定义 JsonConverter 的 ReadJson 方法中处理空对象

在 Android 中使用带有 post 参数的 HttpClient 和 HttpPost

[__NSCFNumber 长度]:发送到实例 UITableView 的无法识别的 Select 器

与classic 规范化表相比,postgres JSON 索引是否足够高效?

JSON - 是否有任何 XML CDATA 类似功能?

使用 JSON (iOS) 的 Cocoa 错误 3840

使用 JSONPath 从 JSON 对象中获取单个值