字符串中的JSON对象不返回字符串

时间:2015-08-06 17:20:34

标签: javascript json

我试图从我的JSON对象中获取一些信息,并且我在控制台上一直收到错误消息:

Uncaught TypeError: Cannot read property 'queue' of undefined". 

我有这个json:

{
    "qmd_file": {
        "queue": "rr7323-psp",
        "name": "unicode",
        "full_path": "/devl/data/queue‌​s/psp/rr7323/unicode",
        "mtime": "2015-05-08T19:02:06.000-04:00"
    }
}

我希望能够获得队列名称“rr7323-psp”。这是我的代码:

function searchFile (qid, filename) {
  var searchUrl = queue_web_services_base + "/q/v1/find.json?qgid="
                + encodeURIComponent(qid) + "&filename="
                + encodeURIComponent(filename);
  var token = encodeURIComponent(window.bpub.authToken);
  $.ajax({
    type: "GET",
    url: searchUrl,
    headers: {'Authorization' : 'Token token="' + token + '"'},
    success: function(json) {
      var jsonString = JSON.stringify(json);
      obj = JSON.parse(jsonString);
      console.log(obj.qmd_file[1].queue);
    }
  });

  return searchUrl;
}

self.searchForFile = function() {
  var queueGroup = prompt ("Please eneter Queue group" , "") 
  var fileName = prompt ("Please enter file name: " , "")
  console.log(searchFile(queueGroup, fileName));
}

3 个答案:

答案 0 :(得分:1)

您有obj.qmd_file[1].queue,但qmd_file节点不是数组。 queueobj.qmd_file的直接后代属性。试试obj.qmd_file.queue

答案 1 :(得分:1)

您正尝试使用以下语句访问JSON中的queue元素:obj.qmd_file[1].queue。此代码表示“获取'obj'对象中'qmd_file'数组中第二个对象的'queue'属性。”

但是,在您发布的JSON中,“qmd_file”是一个对象,而不是一个数组。请尝试使用此代码:obj.qmd_file.queue

答案 2 :(得分:1)

您可以将其作为

获取
console.log(obj.qmd_file.queue);

queue是被提取为obj.qmd_file的对象中的属性,而qmd_file肯定不是数组。

相关问题