简体   繁体   English

JSON响应不是普通对象

[英]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 这是来自获取Django应用程序所有对象的请求,而不是获取普通对象,因为印刷品说它只是一个字符串

Javascript : Javascript:

  $.getJSON("/cadastro/getAllPessoas/", function(data){
    console.log(data);
    console.log(typeof(data));
    console.log($.isPlainObject(data));
    //Raises error on isArrayLike():
    $.each(data,function(){
      arrayValues.push([this["pk"],this["fields"]["nome"]]);
    })
  });

Console output : 控制台输出:

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

views.py : views.py:

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

You're serializing twice in the Django view, because both serializers.serialize and JsonResponse convert to JSON. 您正在Django视图中进行两次序列化,因为serializers.serialize和JsonResponse都转换为JSON。 Don't do that; 不要那样做 just return a normal response with the serialized value. 只需返回带有序列化值的正常响应即可。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM