1

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'
});
8
  • 1
    I believe with jquery.ajax, a) you don't need to JSON.stringify the input data, and you don't need to JSON.parse the success data with the contentType/dataType you have set in the function call ... i.e. you should pass in a plain ol' js object, and you will receive a plain ol' js object Commented Oct 18, 2016 at 23:24
  • alert(data.resp[0].Key); Commented Oct 18, 2016 at 23:26
  • you can alert(JSON.stringify(data)) to show the data in a string. also for your second alert, it should be json.resp[0].id because you're only showing one object in the array Commented Oct 18, 2016 at 23:31
  • @JaromandaX your first point is not correct. In order to send a JSON request body, you need to do what OP is doing. Your second point however is correct and is probably the cause of OP's problem Commented Oct 18, 2016 at 23:31
  • On second thought, i guess it depends on what the response is. Commented Oct 18, 2016 at 23:32

1 Answer 1

5

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);
})
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks all for replies. Phil your answer fixed the problem !Thanks
afaik you can omit the contentType: 'application/json; charset=UTF-8', and the JSON.stringify in the request part as well. dataType: 'json', will do those for you as well
@OlleKelderman no it won't. dataType is specifically relating to the response whereas if you want to send a JSON formatted request body instead of application/x-www-form-urlencoded, you need to provide a data string and set the appropriate contentType.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.