关于Django中JsonResponse返回中文字典编码错误的解决方案
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了关于Django中JsonResponse返回中文字典编码错误的解决方案,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2154字,纯文字阅读大概需要4分钟。
内容图文
解决方案: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并返回响应,前端渲染编码错误的问题。
原文:https://www.cnblogs.com/wf-skylark/p/9317096.html
内容总结
以上是互联网集市为您收集整理的关于Django中JsonResponse返回中文字典编码错误的解决方案全部内容,希望文章能够帮你解决关于Django中JsonResponse返回中文字典编码错误的解决方案所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。