How do I JSON serialize a Python dictionary?

后端 未结 5 2309
余生分开走
余生分开走 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:48

    Update: Python now has its own json handler, simply use import json instead of using simplejson.


    The Django serializers module is designed to serialize Django ORM objects. If you want to encode a regular Python dictionary you should use simplejson, which ships with Django in case you don't have it installed already.

    import json
    
    def json_response(something):
        return HttpResponse(json.dumps(something))
    

    I'd suggest sending it back with an application/javascript Content-Type header (you could also use application/json but that will prevent you from debugging in your browser):

    import json
    
    def json_response(something):
        return HttpResponse(
            json.dumps(something),
            content_type = 'application/javascript; charset=utf8'
        )
    

提交回复
热议问题