Tuesday, May 3, 2011

How do I JSON serialize a Python dictionary?

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

def json_response(something):
    data = serializers.serialize("json", something)
    return HttpResponse(data)

I'm using it like this:

return json_response({ howdy : True })

But I get this error:

"bool" object has no attribute "_meta"

Any ideas?

EDIT: Here is the traceback:

http://dpaste.com/38786/

From stackoverflow
  • 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.

    from django.utils import simplejson
    
    def json_response(something):
        return HttpResponse(simplejson.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):

    from django.utils import simplejson
    
    def json_response(something):
        return HttpResponse(
            simplejson.dumps(something),
            content_type = 'application/javascript; charset=utf8'
        )
    
    Dave : Use JSONView in Firefox to nicely format JSON returned with the application/json content type.
    Dave : That was supposed to be a link to https://addons.mozilla.org/en-US/firefox/addon/10869
  • 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')
    
    Justin Hamade : Thats a good idea i'll probably use this

0 comments:

Post a Comment