How do I parse a JSON multidimensional array in jQuery?

14,141

Solution 1

Try this:

for(var key in data) {
    if(typeof data[key] === "object") {
        for(var i = 0; i < data[key].length; i++) {
            for(var property in data[key][i]) {
                 alert(property + " = " + data[key][i][property]);
            }
        }
    } else if(typeof data[key] === "string") {
        alert(key + " = " + data[key]);
    }
}

Solution 2

If your data is a JSON string, you need to decode it to object first. Use JSON.parse.

Share:
14,141
Akhil Jain
Author by

Akhil Jain

I aspire to attempt and accomplish goals I set for myself. I am highly motivated and make sure I always give my 100% to what I truly believe in. Thoughtful and determined through work, I try to be a better person and take every opportunity to analyse myself, improve and strive hard... http://media.creativebloq.futurecdn.net/sites/creativebloq.com/files/images/2013/06/16-logo.jpg

Updated on June 04, 2022

Comments

  • Akhil Jain
    Akhil Jain about 2 years

    Here is my JSON which I need to parse:

    {"opcode":"groupdetails",
     "status":"success",
     "data":[{"Group ID":5,"Group Name":"data structure","Group Subject":"computer science","Role Type":"Teacher"},{"Group ID":4,"Group Name":"information technology","Group Subject":"computer science","Role Type":"Student"},{"Group ID":6,"Group Name":"data mining","Group Subject":"computer science","Role Type":"Parent"},{"Group ID":7,"Group Name":"dccn","Group Subject":"computer science","Role Type":"Teacher"}]}
    

    I have tried and implemented the solution provided here and this is the implementation of JS that was defined in there solution, which parses only the JSON array

    for (var i = 0; i < data.data.length; i++) 
     {
        var object = data.data[i];
         for (property in object) 
         {
            var value = object[property];
            alert(property + "=" + value);
         }
     }
    

    the outer JSON data is returned from server and yes I have tried parsing using the following code and there is no result:

    for (var i = 0; i < data.length; i++) 
    {
     var object = data[i];
     for (property in object) 
     {
        var value = object[property];
        alert(property + "=" + value);
     }
    }
    

    How can I parse the entire JSON using a single method instead of parsing the JSON array separately?