[Django]-How do I JSON serialize a Python dictionary?

75๐Ÿ‘

โœ…

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'
    )
๐Ÿ‘คSimon Willison

34๐Ÿ‘

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')
๐Ÿ‘คFilippo Vitale

15๐Ÿ‘

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.

6๐Ÿ‘

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 })
๐Ÿ‘คSalvador Dali

2๐Ÿ‘

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
๐Ÿ‘คWaqas

Leave a comment