如何将JSON文件中指定字段值存入JavaScript数组?附问题代码
JSON数据提取问题:代码修复与优化方案
Hey there! Let's break down the issues in your code and fix them step by step:
问题分析
- 字符串字面量
'i'而非变量引用:在循环里你用了jsonFile.captions['i'],这里的'i'是固定字符串,不是循环变量i。而你的JSON键是"1"、"2"、"3",所以应该用动态的键值来访问对应条目。 - 属性名拼写错误:你的JSON里定义的是
endTime,但代码里写的是stopTime,这会导致无法获取对应的值。 - 硬编码循环次数:你写了
i<3,如果后续JSON里的字幕条目数量变化,这段代码就会失效,最好动态获取条目数量。 - 未声明循环变量:
i没有用let/const声明,会变成全局变量,不符合现代JavaScript规范。
修复后的代码(基于原结构)
var arrStart = new Array(); var arrStop = new Array(); var arrGerman = new Array(); var arrEnglish = new Array(); var jsonFile = {}; var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { jsonFile = JSON.parse(this.responseText); // 动态获取所有字幕条目的键,比如["1","2","3"] const captionKeys = Object.keys(jsonFile.captions); for (let i = 0; i < captionKeys.length; i++) { const key = captionKeys[i]; const currentCaption = jsonFile.captions[key]; arrStart.push(currentCaption.startTime); arrStop.push(currentCaption.endTime); // 修复属性名错误 arrEnglish.push(currentCaption.english); arrGerman.push(currentCaption.german); } // 测试输出结果 console.log('Start Times:', arrStart); console.log('End Times:', arrStop); console.log('German Captions:', arrGerman); console.log('English Captions:', arrEnglish); } }; xmlhttp.open("GET", "captions.json", true); xmlhttp.send();
更简洁的ES6写法(推荐)
如果你的运行环境支持现代JavaScript语法,推荐使用fetchAPI替代XMLHttpRequest,代码更简洁且支持Promise:
const arrStart = []; const arrStop = []; const arrGerman = []; const arrEnglish = []; // 用fetch发起网络请求 fetch('captions.json') .then(response => { if (!response.ok) throw new Error('Network response was not ok'); return response.json(); }) .then(data => { // 遍历所有字幕对象 Object.values(data.captions).forEach(caption => { arrStart.push(caption.startTime); arrStop.push(caption.endTime); arrGerman.push(caption.german); arrEnglish.push(caption.english); }); // 测试输出 console.log('Start Times:', arrStart); console.log('End Times:', arrStop); console.log('German Captions:', arrGerman); console.log('English Captions:', arrEnglish); }) .catch(error => console.error('Error loading or parsing JSON:', error));
内容的提问来源于stack exchange,提问作者Romanski133
相关产品推荐
相关产品推荐

