Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I JSON serialize a Python dictionary?

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'
    )

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')

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.


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 })