I have a web method that is returning this json data:
{
"TotalItems":25,
"Assets":
[
{"Id":"49c1fc23-edab-4087-bf3b-884b16399e4b"},
{"Id":"5f8f5aaa-dcfa-4a3f-ae21-b7a9683551e5"},
{"Id":"f589f567-c4d0-49e8-acf4-d3dcd1813b4d"},
{"Id":"b5678b13-1d07-4be5-9c70-02f8475de771"}
]
}
Here's my ajax call and the method I call when the data returns.
$.ajax({
type: "POST",
url: "/Services.asmx/GetAssets",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(results) {
alert(results["d"]); // alerts json above
alert(results.d); // alerts json above
// all of these alert "undefined"
alert(results["d"]["TotalItems"]);
alert(results["d"].TotalItems);
alert(results.d["TotalItems"]);
alert(results.d.TotalItems);
}
});
How can I access the data inside the json result?
I have a web method that is returning this json data:
{
"TotalItems":25,
"Assets":
[
{"Id":"49c1fc23-edab-4087-bf3b-884b16399e4b"},
{"Id":"5f8f5aaa-dcfa-4a3f-ae21-b7a9683551e5"},
{"Id":"f589f567-c4d0-49e8-acf4-d3dcd1813b4d"},
{"Id":"b5678b13-1d07-4be5-9c70-02f8475de771"}
]
}
Here's my ajax call and the method I call when the data returns.
$.ajax({
type: "POST",
url: "/Services.asmx/GetAssets",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(results) {
alert(results["d"]); // alerts json above
alert(results.d); // alerts json above
// all of these alert "undefined"
alert(results["d"]["TotalItems"]);
alert(results["d"].TotalItems);
alert(results.d["TotalItems"]);
alert(results.d.TotalItems);
}
});
How can I access the data inside the json result?
Share asked Oct 16, 2012 at 18:03 StevenSteven 18.9k74 gold badges204 silver badges303 bronze badges 2-
1
i think the
results.d
is a string and you should useJSON.parse(results.d)
before accessing any properties. – Amareswar Commented Oct 16, 2012 at 18:06 -
what about
results.TotalItems
– subodh Commented Oct 16, 2012 at 18:16
2 Answers
Reset to default 4You probably want to use JSON.parse in order to turn the returned JSON into an actual javascript object.
var parsed = JSON.parse(results.d);
parsed.TotalItems //Allow access of total items variable from JSON
You can read more about this at http://www.json/js.html
i think the results.d
is a string and you should use JSON.parse(results.d)
before accessing any properties.