Django: how to generate json response.

It's a common practice to generate content different from standart HTML output by HttpResponce. Lets consider Example on how to generate JSON response by Django.

First of all! Django has built in "other response generators". Most common task is to generate JSON. In general it's extremely easy. Operation called "seriliazation". Official Django docs say:

Django’s serialization framework provides a mechanism for “translating” Django objects into other formats. Usually these other formats will be text-based and used for sending Django objects over a wire, but it’s possible for a serializer to handle any format (text-based or not). "

Anyway an example, helped me a lot.

from django.utils import simplejson
def some_view(request):
    result = []
    result.append({"user":request.user})
    result
.append({"key":request.session.key})     return HttpResponse(simplejson.dumps(result), mimetype='application/json')
In response you will get a nice JSON. 
Hope this will help someone to save some time.  Please leave me a comment if you have something to add/correct... 


Comments

  1. I think this one is more efficient as it streams JSON and does not buffer it to the memory on the server-side before starting the response:

    resp = HttpResponse(content_type="application/json")
    json.dump(result, resp)
    return resp

    ReplyDelete

Post a Comment

Popular posts from this blog

Django: Resetting Passwords (with internal tools)

Time Capsule for $25

Vagrant error: * Unknown configuration section 'hostmanager'.