如何从JSON中的Ajax响应中获取对象信息

时间:2018-01-11 19:48:27

标签: javascript jquery json ajax django

我正在一个需要解析Ajax响应的网站上工作,如下所示:

{"comments": "[{\"model\": \"modelhandler.comment\", \"pk\": 4, \"fields\": {\"user\": 2, \"description\": \"hello this is a comment but I don't know if it's working yet.......\", \"replyto\": null, \"uploaded\": \"2018-01-10T20:35:40.856Z\", \"updated\": \"2018-01-10T20:35:40.856Z\"}}]"}

我尝试从这个响应中获取数据:

success: function (data) {
    var json = JSON.parse(JSON.stringify(data));
    $.each(json, function(key,value) {
        alert(value.comments);
    });
}

然而,这会提醒我undefined

这里注释字段中有1个注释,但我可能有超过1.如何从这样的Json响应中检索数据?

编辑:

我记录了data对象,我得到了这个:

Object
comments
:
"[{"model": "modelhandler.comment", "pk": 4, "fields": {"user": 2, "description": "hello this is a comment but I din't know if it's working yet.......", "replyto": null, "uploaded": "2018-01-10T20:35:40.856Z", "updated": "2018-01-10T20:35:40.856Z"}}]"
__proto__
:
Object
使用console.log()

在谷歌浏览器中

json也是由django视图生成的:

def obtain_comments(request, *args, **kwargs):
    begin = int(request.GET['begin'])
    end = int(request.GET['end'])
    n_comments = end - begin
    all_split = Comment.objects.order_by('-uploaded')[:end]
    data = {
        'comments': serializers.serialize('json',all_split),
    }
    return JsonResponse(data)

1 个答案:

答案 0 :(得分:5)

看起来您的回复是一个对象,并且值已经过字符串化。

尝试

success: function (data) {
  var comments = JSON.parse(data.comments);
  // comments is an array now
  comments.forEach(function(comment) {
    console.log(comment.fields.description);
  });
}

如果您要在Django中序列化整个数据对象而不仅仅是注释,那会更好。