【发布时间】:2020-03-02 05:08:48
【问题描述】:
尝试从本地文件中获取json数据并不断获取
“JSON.parse:第 1 行第 1 列的数据意外结束”。
我已经为 fetch 函数尝试了许多参数,但始终出现至少 1 个错误。
function getData() {
fetch('./data.json', {mode: 'no-cors'})
.then((res) => res.json())
.then((data) => {
console.log(data);
})
};
JSON 数据
{
"CustomerJohn": [
{
"month": "April",
"transaction": 1,
"price": 57
},
{
"month": "April",
"transaction": 2,
"price": 89
},
{
"month": "May",
"transaction": 1,
"price": 163
},
{
"month": "May",
"transaction": 2,
"price": 43
},
{
"month": "May",
"transaction": 3,
"price": 221
},
{
"month": "June",
"transaction": 1,
"price": 99
},
{
"month": "June",
"transaction": 2,
"price": 201
}
]
}
我想控制台记录数据以确保其正常运行。
【问题讨论】:
-
获取数据时可能出错。您能否检查一下 chrome 开发工具的网络选项卡,调用返回的内容。
-
你发布的JSON是有效的,所以在实际应用中肯定有不同的地方。
-
正如 Nicolas 所说,我会假设响应的第 1 行类似于换行符之类的东西,而实际的 JSON 数据从第 2 行开始。
-
Chrome 是这么说的
-
app.js:20 Fetch API 无法加载 file:///C:/data.json。不支持 URL 方案“文件”。 getData @ app.js:20 app.js:20 Uncaught (in promise) TypeError: Failed to fetch at HTMLButtonElement.getData (app.js:20)
标签: javascript json fetch