user1788736 user1788736 - 1 month ago 6
Javascript Question

How to access json object using javascrpt?

I am not an expert in json parsing so please bear with me if i ask simple question.I have a json response like this :

{
"resp": [{
"Key": "123423544235343211421412",
"id": "12"
}]
}


I want to access value of key and id (123423544235343211421412,12)
.I tried following but i can't get the values! I appreciate if you guys show me how to get those values.Thanks

var postData = {
Name: "Galaxy",
action: "token"
};

$.ajax("https://someapiurl/getit.aspx",
{
type : 'POST',
data: JSON.stringify(postData),
contentType: "application/json",

success: function(data) {

var json = JSON.parse(data);
alert(json.resp[0].Key);
alert(json.resp[1].id);
},
contentType: "application/json",
dataType: 'json'
});

Answer

You're almost there. jQuery automatically parses the response as JSON for you when you specify dataType: 'json'

$.ajax('https://someapiurl/getit.aspx', {
    method: 'POST',
    contentType: 'application/json; charset=UTF-8',
    dataType: 'json',
    data: JSON.stringify(postData)
}).done(function(obj) {
    alert(obj.resp[0].Key);
    alert(obj.resp[0].id);
})
Comments