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) {

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?


I logged data object and I got this:

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

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.


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

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