如何使用javascript访问json对象?

use*_*736 1 javascript arrays json

我不是json解析的专家所以如果我问一个简单的问题,请耐心等待.我有一个像这样的json响应:

{
    "resp": [{
        "Key": "123423544235343211421412",
        "id": "12"
    }]
}
Run Code Online (Sandbox Code Playgroud)

我想访问密钥和id的值(123423544235343211421412,12).我试过以下但我无法获取值!

如果你们让我们告诉我如何获得这些价值,我感激不尽.谢谢

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'
});
Run Code Online (Sandbox Code Playgroud)

Phi*_*hil 5

你快到了.当您指定时,jQuery会自动将响应解析为JSONdataType: '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);
})
Run Code Online (Sandbox Code Playgroud)