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

BRH*_*HSM 1 javascript django ajax jquery json

我正在一个需要解析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\"}}]"}
Run Code Online (Sandbox Code Playgroud)

我尝试从这个响应中获取数据,如下所示:

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

然而,这提醒了我 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
Run Code Online (Sandbox Code Playgroud)

在谷歌浏览器中使用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)
Run Code Online (Sandbox Code Playgroud)

lan*_*nan 5

看起来您的响应是一个对象,值是字符串化的.

尝试

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

如果你在Django中序列化整个数据对象而不仅仅是注释会更好.