解决方案:JsonResponse(data, json_dumps_params={'ensure_ascii':False})

! data是需要渲染的字典

def master(request):
data = {'这是':'主页'}
return JsonResponse(data, json_dumps_params={'ensure_ascii':False})

 显示效果: 

首先我们看JsonResponse()的源码:

class JsonResponse(HttpResponse): 

  def __init__(self, data, encoder=DjangoJSONEncoder, safe=True,
    json_dumps_params=None, **kwargs):     if safe and not isinstance(data, dict):
      raise TypeError(
      'In order to allow non-dict objects to be serialized set the '
      'safe parameter to False.'
      )
    if json_dumps_params is None:
      json_dumps_params = {}
    kwargs.setdefault('content_type', 'application/json')
    data = json.dumps(data, cls=encoder, **json_dumps_params)
    super(JsonResponse, self).__init__(content=data, **kwargs)

 这里我们从根源开始找它编码错误的原因:

JsonResponse()在初始化的时候使用了json.dumps()把字典转换成了json格式,具体方法如下:

data = json.dumps(data, cls=encoder, **json_dumps_params)

接下来我们看看json.dumps()的源码:

def dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True,
allow_nan=True, cls=None, indent=None, separators=None,
default=None, sort_keys=False, **kw):
if (not skipkeys and ensure_ascii and
check_circular and allow_nan and
cls is None and indent is None and separators is None and
default is None and not sort_keys and not kw):
return _default_encoder.encode(obj)
if cls is None:
cls = JSONEncoder
return cls(skipkeys=skipkeys, ensure_ascii=ensure_ascii,
check_circular=check_circular, allow_nan=allow_nan,
indent=indent,separators=separators, default=default,
sort_keys=sort_keys,**kw).encode(obj)

源码注释原文:If ``ensure_ascii`` is false, then the return value can contain non-ASCII characters if they appear in strings contained in ``obj``. Otherwise, all such characters are escaped in JSON strings.

也就是说ensure_ascii是false的时候,可以返回非ASCII码的值,否则就会被JSON转义。

所以含有中文的字典转json字符串时,使用 json.dumps() 方法要把ensure_ascii参数改成false,即 json.dumps(dict,ensure_ascii=False)。

JsonResponse()接收参数有关键词参数,json_dumps_params=None ,用来给 json.dumps() 传参,所以 要在关键字参数后面拼个字典来传另一组关键字参数 ensure_ascii=False,即:

json_dumps_params={'ensure_ascii':False}

综上可解决使用 JsonResponse() 强制把含有中文的字典转json并返回响应,前端渲染编码错误的问题。

关于Django中JsonResponse返回中文字典编码错误的解决方案的更多相关文章

  1. django JsonResponse返回中文时显示unicode编码(\u67e5\u8be2)

    django JsonResponse返回中文时显示unicode编码(\u67e5\u8be2) 关注公众号"轻松学编程"了解更多. 原因 这个unicode编码,是python ...

  2. Django中不返回QuerySets的API -- Django从入门到精通系列教程

    该系列教程系个人原创,并完整发布在个人官网刘江的博客和教程 所有转载本文者,需在顶部显著位置注明原作者及www.liujiangblog.com官网地址. Python及Django学习QQ群:453 ...

  3. django管理数据库之中文字符编码问题

    django中通过models创建数据库字符编码文字mysql数据库中默认的字符编码都为latin1,插入中文时会出现以下的错误类型 1366 - Incorrect string value: '\ ...

  4. [UnicodeEncodeError]:Django中解决URL中文解释乱码问题

    Django中在使用HttpResponseRedirect的时候,跳转URL中如果存在中文,会报错:会报UnicodeEncodeError错误. 解决办法: 使用urlquote对URL进行编码 ...

  5. Django中的 返回json对象的方式

    在返回json对象的几种方式: 1 from django.shortcuts import render, HttpResponse # Create your views here. from d ...

  6. python3下urlopen解析中文url编码错误

    这是在ipython下测试的结果: In [24]: x Out[24]: 'http://127.0.0.1:8000/xxx/?id=a45ex0bad3c9&game=五子棋' In [ ...

  7. JsonResponse返回中文乱码问题

    class Publish(APIView): def get(self, request): publish_list = models.Publish.objects.all() bs = MyS ...

  8. Python中的解决中文字符编码的问题

    python3中str默认为Unicode的编码格式 python2中str默认为bytes类型的编码格式 Unicode是一32位编码格式,不适合用来传输和存储,所以必须转换成utf-8,gbk等等 ...

  9. 处理springMvc中responsebody返回中文乱码

    法一:   @RequestMapping(value="/getUsersByPage",produces = public String getUsers  法二:在sprin ...

随机推荐

  1. EMSAscript

    1.javaScript 中const.var.let区别 const 定义的变量不可修改 而且必须初始化 =>解决闭包变量污染问题 var 定义的变量可以修改 如果不初始化则默认值为undef ...

  2. 【Python】directory字典类型

    它的基本格式是(key是键,value是值): d = {key1 : value1, key2 : value2 } Example dir = {'Mic':1,'Sun':2} for k in ...

  3. 使用Mist部署Contract到Rinkeby以太坊网络

    本文使用MyEthWallet新建一个账号,并导入到Mist中,然后部署Contract到Rinkeby网络使用MyEthWallet新建账号的好处是除了JSON文件之外,还能得到一张它生成的pdf( ...

  4. SpringMVC学习(一)——概念、流程图、源码简析

    学习资料:开涛的<跟我学SpringMVC.pdf> 众所周知,springMVC是比较常用的web框架,通常整合spring使用.这里抛开spring,单纯的对springMVC做一下总 ...

  5. 【Leetcode】【Medium】Word Break

    Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separa ...

  6. UIButton的titleLabel

    UIButton的titleLabel @property(nonatomic, readonly, retain) UILabel *titleLabel Description - 描述A vie ...

  7. zookeeper 的监控工具

    zookeeper 的监控工具         公司很多产品会使用zookeeper,比如Meta消息中间件,在测试的过程中,我们经常需要查询zookeeper里面的信息来精确定位问题.目前项目中有开 ...

  8. JS 和 Jq 获取客户端各种屏幕宽度和高度

    //javascript 网页可见区域宽: document.body.clientWidth 网页可见区域高: document.body.clientHeight 网页可见区域宽: documen ...

  9. 设计模式:解释器(Interpreter)模式

    设计模式:解释器(Interpreter)模式 一.前言 这是我们23个设计模式中最后一个设计模式了,大家或许也没想到吧,竟然是编译原理上的编译器,这样说可能不对,因为编译器分为几个部分组成呢,比如词 ...

  10. gogs配置及迁移

    工作需要迁移gogs,粗略记下笔记 操作系统:CentOS Linux release 7.4.1708 (Core) 防火墙:关闭状态,如有需要开启默认的3000端口 一.配置 首先安装git [r ...