How do I JSON serialize a Python dictionary?

后端 未结 5 2286
余生分开走
余生分开走 2020-12-07 11:06

I\'m trying to make a Django function for JSON serializing something and returning it in an HttpResponse object.

def json_response(something):
          


        
5条回答
  •  轮回少年
    2020-12-07 11:46

    What about a JsonResponse Class that extends HttpResponse:

    from django.http import HttpResponse
    from django.utils import simplejson
    
    class JsonResponse(HttpResponse):
        def __init__(self, data):
            content = simplejson.dumps(data,
                                       indent=2,
                                       ensure_ascii=False)
            super(JsonResponse, self).__init__(content=content,
                                               mimetype='application/json; charset=utf8')
    

提交回复
热议问题