使用JavaScript读取JSON文件遇TypeError: Failed to fetch错误求助
解决本地JSON文件读取的Fetch错误及路径解析问题
问题概述
编写异步函数readJSONFile用于读取本地JSON文件并返回指定路径对应的值,预期输出1.15,但运行时触发错误:
script.js:25 Failed to read JSON file: TypeError: Failed to fetch
文件结构:当前目录下存在script.js和Items.json两个文件。
原代码与JSON内容
script.js
async function readJSONFile(path) { const [filePath, jsonPath] = path.split('|'); try { const response = await fetch(filePath); if (!response.ok) { throw new Error(`Network response was not ok: ${response.statusText}`); } const jsonData = await response.json(); const keys = jsonPath.split('/'); let value = jsonData; for (const key of keys) { if (Array.isArray(value) && !isNaN(key)) { value = value[parseInt(key)]; } else { value = value[key]; } if (value === undefined || value === null) { return undefined; } } return value; } catch (error) { console.error(`Failed to read JSON file: ${error}`); return undefined; } } const path = 'Items.json|Data/taxValue'; readJSONFile(path).then(result => console.log(result)); // 预期输出1.15
Items.json
{ "Data": [ { "taxValue": 1.15 } ], "Fruits": [ { "name": "apple", "cost": 1.59, "tax": true, "itemId": 12345, "ect...": 0 } ], "Others": [] }
错误原因
- Fetch本地文件限制:浏览器出于安全策略,不允许
fetch直接访问file://协议下的本地文件,必须通过HTTP服务器托管资源后访问。 - JSON路径解析错误:原路径
Data/taxValue未考虑Data是数组类型,需要指定数组索引才能定位到包含taxValue的对象。
修复方案
1. 启动本地HTTP服务器
通过本地服务器以HTTP协议访问文件,规避浏览器的本地文件访问限制:
- 方法一:使用VS Code的Live Server插件,右键点击关联的HTML文件(无HTML可新建空白文件并引入
script.js),选择「Open with Live Server」。 - 方法二:使用Node.js的
http-server工具,全局安装后在文件目录执行命令:
访问控制台输出的本地地址(如npm install -g http-server http-serverhttp://localhost:8080)即可加载资源。
2. 修正JSON路径
将路径中的Data/taxValue修改为Data/0/taxValue,明确指定数组索引:
const path = 'Items.json|Data/0/taxValue';
完成上述修改后重新运行,即可正确输出1.15。
内容的提问来源于stack exchange,提问作者Yu-Hayate
相关产品推荐
相关产品推荐

