如何通过key访问json数组

时间:2013-12-29 03:16:23

标签: javascript jquery json x-editable

当我打印时:console.log( response );

它给了我这个json数组:

{    
    "myStudentId":17,
    "myName":"beng",
    "myAge":38,
    "myAddress":"Los Angeles, California, USA.",
    "myGender":"Female",
    "myReligion":"Catholic",
    "myStatus":"boom",
    "myOccupation":"Actress",
    "myEducationLevel":"Undefined",
    "graduate":true
}

我想访问graduate值。我到目前为止尝试的是:

console.log( response["graduate"] );
console.log( response.graduate );

但是这一切都返回undefined。有没有办法做到这一点?如果可能的话我不想使用循环。如果可能,我想通过密钥访问它。

修改

我正在使用x-editable success method进行回电。

$(this).editable({
    pk: pk,
    name: id,
    url: '../admin/edit_studentInfo.do',
    validate: function( value ) {
       if($.trim( value ) == '') {
          return 'This field is required';
       } else if( isNaN( value ) && id == 'age' ) {
          return 'Only accepts numbers';
       }
        },
    success: function(response, newValue) { // call back
       var test = response;
       console.log( JSON.stringify(response) );
       console.log( response );
       console.log( response["graduate"] );
       console.log( response["myName"] + ', ' + response.myName );
    }
});

我包含了我的可编辑初始化以及测试

2 个答案:

答案 0 :(得分:3)

response是一个字符串。您需要先将其解析为JSON,然后才能访问编码对象的任何属性:

response = JSON.parse(response);
console.log(response.graduate);

或者,告诉使用$.getJSON或传递dataType : "JSON",jQuery将为您解析。

答案 1 :(得分:0)

添加ajaxOption

ajaxOptions: {
dataType: 'json'
}