1

I am stuck with a problem while parsing the response data in json format.

JSON Output from an external URL:

[
{
    "id": "1",
    "qtext": "Do you like this product?",
    "op": [
        {
            "oid": "1",
            "option": "option1"
        },
        {
            "oid": "2",
            "option": "option2"
        },
        {
            "oid": "3",
            "option": "option3"
        },
        {
            "oid": "4",
            "option": "option4"
        }
    ]
  },
    {
    "id": "16",
    "qtext": "How is the quality of this video?",
    "op": []
    }
]

To parse this json, I have written this jQuery code:

    $.ajax({
    type: 'POST',
    url: 'jsonexp1.php',
        data: {id:1},
        success: function(data) {
            var pj = $.parseJSON(data);
            $.each(pj,function(k,element){
            $("#content").html($("#content").html()+"<p>"+element.id+" "+element.qtext);
        });
    }
});

I am able to read the first two items "id" and "qtext" from the json output. But, I am unable to traverse the other elements.

A guideline will help. Thanks

4
  • what element you want ? Commented May 8, 2014 at 9:57
  • you need one more $.each() in your current $.each(). Commented May 8, 2014 at 9:58
  • I wish to read option & oid both. I am trying with one more $.each() Commented May 8, 2014 at 10:03
  • Look at Rory McCrossan answer Commented May 8, 2014 at 10:04

2 Answers 2

1

op in the response is an array, so you need another $.each loop.

success: function(data) {
    $.each(data, function(k, element) {
        $.each(data.op, function() {
            // do something with the data in the item...
            console.log(this.oid);
            console.log(this.option);
        });
        $("#content").append($('<p />', { text: element.id + " " + element.qtext });
    });
}

Also, note you can use append() to add an element.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Rory! I am trying this out. Appreciating your instant help.
0

I suggest you this:

var htm = '';
$.each(pj,function(k,element){
    htm = $("#content").html() + "<p>" + element.id + " " + element.qtext;
    $.each(pj.op, function(i, o){
       htm = htm + "<p>" + o.oid + " " + o.option;
    });
});
$("#content").html(htm);

1 Comment

Thanks Jai. Can you help me in displaying the o.option in a <select> drop down list? I am able to parse the entire json now.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.