Miranda Miranda - 2 months ago 8
JSON Question

How do I access the result inside json data concept?

Can anyone explain me how do i access the result of json data.
here is my json value which is i am getting inside ajax success by doing

success: function (data) {
console.log(data.d)
console.log("Success")
},


For above code what I'm getting is:

{
"locations": {
"location": [{
"invid": "1634",
"usrinvid": "1",
"locname": "My Location",
"businessunit": "My Business Unit",
"organization": "My Organization",
"desc": "This is the location created by the system for the new Business Owner. It can be renamed.",
"netqtyavail": "0.000"
}, {
"invid": "1647",
"usrinvid": "2",
"locname": "My Second Location",
"businessunit": "My Business Unit",
"organization": "My Organization",
"desc": null,
"netqtyavail": "0.000"
}, {
"invid": "1698",
"usrinvid": "20",
"locname": "test dsf - Loc 1",
"businessunit": "test dsf",
"organization": "My Organization",
"desc": "This location was added compulsorily for the new business unit -'test dsf'. You can update the name, description and other details of this location. You may also delete this location if you have added other location for 'test dsf'",
"netqtyavail": "0.000"
}]
}
}


And after parsing those result inside success like:

success: function (data) {
console.log(JSON.parse(data.d))
console.log("Success")
},


results are:

enter image description here

Answer

The return value of JSON.parse(data.d), in your case, is an object:

var obj = JSON.parse(data.d);

You use that object's properties just like you do any other object's properties.

The object in your question is a bit odd: It has just one property, called locations, which is an object that also has just a single property, location, which is an array of locations. I say that's odd because 1. It seems like an unnecessary level of nesting, and 2. location is an odd name for an array of locations (plural).

However, if we want to access those locations, we can do so in the normal way:

console.log(obj.locations.location.length); // 3

Or you could list the names of those locations by looping through the array:

obj.locations.location.forEach(function(entry) {
    console.log(entry.locname);
});

Etc.