Creating a JSON Response Using Django and Python

Creating a JSON response using Django and Python

I usually use a dictionary, not a list to return JSON content.

import json

from django.http import HttpResponse

response_data = {}
response_data['result'] = 'error'
response_data['message'] = 'Some error message'

Pre-Django 1.7 you'd return it like this:

return HttpResponse(json.dumps(response_data), content_type="application/json")

For Django 1.7+, use JsonResponse as shown in this SO answer like so :

from django.http import JsonResponse
return JsonResponse({'foo':'bar'})

how to return json response from views.py instead of .html file in django

You can create a view that returns a JsonResponse:

from django.http import JsonResponse

def some_view(request):
return JsonResponse({'some_key': 'some_value'})

(…) is a dictionary that is having keys and values from multiple model classes

You can simply pass model objects as JSON. In that case you need to serialize this properly. You can use Django's serialization framework, or work with a Serializer from the Django REST framework. The Django REST framework also offers a lot of tooling for CRUD operations with JSON or XML, etc.

Create JSON Response in Django with Model

You should use django serializers instead of simplejson:

For example, this returns correctly serialized data:

from django.core import serializers
# serialize queryset
serialized_queryset = serializers.serialize('json', some_queryset)
# serialize object
serialized_object = serializers.serialize('json', [some_object,])

How to assign variable to JSON in Django Views.py context

the problem was in the PARAMETER, i had

parameters = { 'slug': 'bitcoin', 'convert': 'USD', }

instead of

parameters = { 'slug': coin.api_slug, 'convert': 'USD', }

Issue with django json response

You can do like this to access related attributes

def getMessages(request):
messages =LivechatMessage.objects.all()
return JsonResponse({"messages":list(messages.values('user__username','user__id'))})

Django get primary key with JSON response

I think this comprehension may lose some values.

serialized_page = serialize("json", page_obj.object_list)

When you call ['fields'] here:

serialized_page = [obj["fields"] for obj in json.loads(serialized_page)]

You get only values of key 'fields'. It's like standard dictionary.

fields = {"first_name": "Dan", "last_name": "ram", "address": "6090 DRAGON WAY", "city": "CREST", "state": "CA", "zipcode": 91912}

Try that:

serialized_page = serialize("json", page_obj.object_list)
serialized_page = [{**obj["fields"], **{"pk": obj["pk"]}} for obj in json.loads(serialized_page)]


Related Topics



Leave a reply



Submit