Saturday, April 4, 2015

Creating a JSON response using Django and Python

Pre-Django 1.7:

import json
from django.http import HttpResponse

def testjson(request):
  response_data = {}
  response_data['result'] = 'failed'
  response_data['message'] = 'You messed up'
  return HttpResponse(json.dumps(response_data), content_type="application/json")

Django 1.7+:

from django.http import JsonResponse

def testjson(request):
  response_data = {}
  response_data['result'] = 'failed'
  response_data['message'] = 'You messed up'
  return JsonResponse(json.dumps(response_data))

Reference:

http://stackoverflow.com/questions/2428092/creating-a-json-response-using-django-and-python

No comments: