Mojimi Mojimi - 9 months ago 36
Javascript Question

JSON response not a plain object

This is coming from a request to get all objects of a Django apps, it is not getting a plain object, as the print says it is just a string

Javascript :

$.getJSON("/cadastro/getAllPessoas/", function(data){
//Raises error on isArrayLike():

Console output :

[{"model": "cadastroapp.djangotestpessoa", "pk": 1, "fields": {"nome": "Gabriel"}}]
false :

from django.core import serializers
def getAllPessoas(request):
data = serializers.serialize('json', Pessoa.objects.all(), fields=('objectid','nome'))
return JsonResponse(data, safe=False)

Answer Source

You're serializing twice in the Django view, because both serializers.serialize and JsonResponse convert to JSON. Don't do that; just return a normal response with the serialized value.

return HttpResponse(data, content_type='application/json')