【问题标题】:Can't access value from JSON无法从 JSON 访问值
【发布时间】:2014-02-24 12:17:23
【问题描述】:

我有这个 JSON 字符串:

{
    "attachedFiles": [{
        "link": "/site.com/dir?id=12993&SESSION=40af90dd-c1f3-4678-93e5-a4b36f3597b0&SESSIONTICKET=SESS:67bf209be2",
        "fileName": "file1.txt",
        "docDate": "24.02.2014",
        "docTime": "13:54",
        "docId": "12993"
    }],
    "requestId": 48,
    "tasksId": 0,
    "workId": 10558
}

我是这样转换的:

var resdata = xhr.responseText; // the string response from the server
var resObj = JSON.parse(resdata);

然后我尝试通过以下代码访问(打印值)fileName 内部的 attachedFiles 对象:

console.log(resObj.attachedFiles.fileName);

它总是返回undefined。我知道我在这里遗漏了一些非常小的东西,但我无法发现它。

【问题讨论】:

标签: javascript jquery


【解决方案1】:

attachedFiles 是数组。所以尝试使用索引器访问数组内容

resObj.attachedFiles[0].fileName // 0th index, 1st Element

访问数组中的所有元素。感谢@Cerbus 评论

for(var i = 0, l = resObj.attachedFiles.length; i < l;i++)
{
   console.log(resObj.attachedFiles[i].fileName);
}

【讨论】:

  • 请注意[0] 访问attachedFiles 数组中的第一个附件。如果要访问数组中可变数量的元素,则必须使用 for 循环迭代数组:for(var i = 0, l = resObj.attachedFiles.length; i &lt; l; i++){console.log(resObj.attachedFiles[i]);}
【解决方案2】:

attachedFiles 是一个array,所以使用indexer 它是从零开始的索引,所以第一个元素将是零索引。

console.log(resObj.attachedFiles[0].fileName);

【讨论】:

    猜你喜欢
    • 2015-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多