python中json格式化中文显示乱码的解决办法

json格式化中文显示乱码的几种情况:

1.在使用json.dumps方法时,添加参数:ensure_ascii=False,默认True

源码解释:如果`ensure_ascii``为false,则返回值可以包含非ascii字符,如果它们出现在“obj”中包含的字符串中。否则,所有此类字符在JSON字符串中进行转义。

import json

"""
    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.
"""
res = json.dumps({"code": 1001, "name": "电波发"}, ensure_ascii=False)

2.在使用django.http.response.JsonResponse时,添加参数:json_dumps_params={"ensure_ascii": False}

其实就是在JsonResponse中使用json.dumps方法并传入参数{"ensure_ascii": False}

from django.http import JsonResponse
"""
    An HTTP response class that consumes data to be serialized to JSON.

    :param data: Data to be dumped into json. By default only ``dict`` objects
      are allowed to be passed due to a security flaw before ECMAScript 5. See
      the ``safe`` parameter for more information.
    :param encoder: Should be a json encoder class. Defaults to
      ``django.core.serializers.json.DjangoJSONEncoder``.
    :param safe: Controls if only ``dict`` objects may be serialized. Defaults
      to ``True``.
    :param json_dumps_params: A dictionary of kwargs passed to json.dumps().
"""

def login(request):
    return JsonResponse({"title": "首页", "name": "电波发"}, json_dumps_params={"ensure_ascii": False})

你可能感兴趣的:(python,python,django,后端)