關於json.dumps中的參數,例如ensure_ascii


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

! data是需要渲染的字典

在使用json.dumps時要注意一個問題 >>> import json >>> print json.dumps('中國') "\u4e2d\u56fd" 輸出的會是 '中國' 中的ascii 字符碼,而不是真正的中文。 這是因為json.dumps 序列化時對中文默認使用的ascii編碼.想輸出真正的中文需要指定ensure_ascii=False: >>> import json >>> print json.dumps('中國') "\u4e2d\u56fd"
>>> print json.dumps('中國',ensure_ascii=False) "中國"
>>> 

 

1
2
3
def  master(request):
     data  =  { '這是' : '主頁' }
     return   JsonResponse(data, json_dumps_params = { 'ensure_ascii' : False })

 顯示效果: 

首先我們看JsonResponse()的源碼:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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格式,具體方法如下:

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

接下來我們看看json.dumps()的源碼:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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並返回響應,前端渲染編碼錯誤的問題。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM