Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing java map returned as JSON response using javascript

I didn't found any specific answer which addresses the below question.

I have the following JSON response fetched through an AJAX POST request.

{
"result":
{
"101010":["PRAVAT","SGSGSG","UKEMP5","UKENTD","WAUK01","MK87UK"],
"202020":["CORA1E","PSASAS","EDCRJS","USHC01","USDR06"],
............................
........................
"304050":["ERCDE2","DELT01","DECGKG","DEHC03","IS02","DEPI01"]
},
"status":"SUCCESS"
}

I want to display the data above data by using a loop in javascript. I tried for ( var i = 0; i < response.result.length; i++) { but I am not able to do so.

Please help how can I parse and display my data in the above JSON format using javascript.

like image 898
Pravat Panda Avatar asked Dec 20 '22 04:12

Pravat Panda


1 Answers

What you have is an object, not an array. Only arrays have the length property. To iterate over an object use:

$.post("yoururlhere", function(JSONData) {
    var obj = $.parseJSON(JSONData);
    if (obj.status.toLowerCase() === "success") {
        for (var key in obj.result) {
            if (obj.result.hasOwnProperty(key)) {
               console.log(key + ': ' + obj.result[key]);
            }
        }
    }
});

The if (obj.result.hasOwnProperty(key)) forces the for to ignore prototype properties. If you care to look it up they are the means you can do inheritance in Javascript.

like image 115
Hoffmann Avatar answered Dec 22 '22 18:12

Hoffmann