如何在Django中执行JSON处理程序 [英] How to do JSON handler in Django

查看:84
本文介绍了如何在Django中执行JSON处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在django视图中获取并解析json.

I want to get and parse json in django view.

模板中最新鲜的

var values = {};
$("input[name^='param']").each(function() {
    values[$(this).attr("name")] = $(this).val();
});

$.ajax
({
    type: "POST",
    url: page,
    contentType: 'application/json; charset=utf-8',
    async: false,
    processData: false,
    data: $.toJSON(values),
    success: function (resp) {
        console.log(resp);

    }
});

视图中:

import json
...
req = json.loads(request.body)
return HttpResponse(req)

它给我错误:

JSON对象必须为str,而不是'bytes'

the JSON object must be str, not 'bytes'

我做错了什么?

推荐答案

大多数Web框架都将字符串表示形式视为utf-8,因此Python 3中的字节(例如Django和Pyramid).在python3中,需要在正文中解码('utf-8'):

Most web framework consider string representation as utf-8, so bytes in Python 3 (like Django, and Pyramid). In python3 needs to decode('utf-8') for body in:

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

这篇关于如何在Django中执行JSON处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆