How do I JSON serialize a Python dictionary?

后端 未结 5 2211
余生分开走
余生分开走 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')
    
    0 讨论(0)
  • 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'
        )
    
    0 讨论(0)
  • 2020-12-07 11:49

    In python 2.6 and higher there is a nice JSON library, which has many functions among which is json.dumps() which serializes an object into a string.

    So you can do something like this:

    import json
    print json.dumps({'howdy' : True })
    
    0 讨论(0)
  • 2020-12-07 11:51

    With newer versions of Django you can just use JsonResponse provided by django.http:

    from django.http import JsonResponse
    
    def my_view(request):
        json_object = {'howdy': True}
        return JsonResponse(json_object)
    

    You can find more details in the official docs.

    0 讨论(0)
  • 2020-12-07 12:05
    import json
    
    my_list = range(1,10) # a list from 1 to 10
    
    with open('theJsonFile.json', 'w') as file_descriptor:
    
             json.dump(my_list, file_descriptor) #dump not dumps, dumps = dump-string
    
    0 讨论(0)
提交回复
热议问题