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'
)
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')
- [Django]-Django 1.8 Run a specific migration
- [Django]-Cannot access django app through ip address while accessing it through localhost
- [Django]-How to resolve AssertionError: .accepted_renderer not set on Response in django and ajax
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.
- [Django]-Actions triggered by field change in Django
- [Django]-Django TypeError: get() got multiple values for keyword argument 'invoice_id'
- [Django]-How to pass information using an HTTP redirect (in Django)
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 })
- [Django]-How to completely uninstall a Django app?
- [Django]-How to set the default of a JSONField to empty list in Django and django-jsonfield?
- [Django]-Django: how can I tell if the post_save signal triggers on a new object?
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
- [Django]-Django rest framework change primary key to use a unqiue field
- [Django]-Django 2.0 โ Not a valid view function or pattern name (Customizing Auth views)
- [Django]-Good open source django project for learning