How to get objct information from Ajax response in JSON

I'm working on a site that needs to parse an Ajax response which looks something like this:

{"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\"}}]"}

I tried getting data from this response like this:

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

This however alerts me undefined

Here the comments field has 1 comment in it but I might have more than 1. How would I go about retrieving data from a Json response like this?

EDIT:

I logged data object and I got this:

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

in Google Chrome using console.log()

also the json is generated by a django view like this:

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 answer

  • answered 2018-01-11 19:48 lanan

    Looks like your response is an object and values are stringified.

    Try

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

    It would be better if you were to serialize entire data object in Django instead of just comments.