我有这个 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);
然后我尝试通过以下代码访问(打印值)attachedFiles
对象内的fileName
:
console.log(resObj.attachedFiles.fileName);
它总是返回未定义
。我知道我在这里错过了一些非常小的东西,但我无法发现它。
最佳答案
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);
}
关于javascript - 无法从 JSON 访问值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21987529/