从json响应中获取变量

时间:2016-09-16 18:44:41

标签: javascript jquery json

我在JSON中有一个GET函数和响应。 这是功能:

$.ajax({
  contentType: 'application/json',
  dataType: 'json',
  success: function(msg){
    var result = JSON.stringify(msg);
    console.log(result);
  },
  error: error,
  type: 'GET',
  url: myurl
});
来自result的成功回应是这样的:

{"response":{"values":[{"name":"john","sex":"male"}]}}

但是当我尝试从响应中获取name时,我收到错误! 这是错误:

for(var k in result){
  console.log(result[k]);
}

显示字母

我试过了:

$.each(result,function(index, value){
    console.log(index, value);
});

但总是会出错。

3 个答案:

答案 0 :(得分:0)

尝试删除JSON.stringify(msg.response)。之后,msg.response.values[0].name 应该给john

答案 1 :(得分:0)

您获得的响应本身就是一个json对象。您可以遍历该对象并从该对象获取名称。

答案 2 :(得分:0)

您可以从json本身访问该值

var response = {"response":{"values":[{"name":"john","sex":"male"}]}};

var getName = response.response.values[0].name;

alert(getName);

相关问题