如何使用javascript访问json对象

How to access json object using javascript?

本文关键字:json 对象 访问 javascript 何使用      更新时间:2023-09-26

我不是json解析专家,所以如果我问一个简单的问题,请原谅我。我有一个json响应像这样:

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

我想访问key和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'
});

你就快成功了。当您指定dataType: 'json'

时,jQuery会自动将响应解析为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);
})