Skip to content Skip to sidebar Skip to footer

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','SG

Solution 1:

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.

Solution 2:

Do you have it as an object or JSON?

To convert the JSON to an object in jquery, use $.parseJSON().

EG. var obj = $.parseJSON(myJSONData);

Once you have the object, you can loop through the keys using:

for (var key in obj) {
    console.log(key + ': ' + obj[key]);
}

Solution 3:

You should parse it, You can use JSON.parse() or jQuery.parseJSON(). Have a look at this: Parse JSON in JavaScript?

Solution 4:

As MostafaR said, you need to parse it into a javascript object first. When you get JSON from somewhere, javascript just considers it a string, so you won't be able to access it directly. Also, some older browsers don't have window.JSON, so you'll need to include the json2.js library if you're worried about support from older browsers.

Post a Comment for "Parsing Java Map Returned As Json Response Using Javascript"