使用 Javascript 从 url 读取 Json 文件
read Json file from url with Javascipt
嘿,我找不到这个简单问题的答案。
我正在构建一个简单的 OpenLayers 项目。
作为项目的一部分,我想在地图上显示所有星巴克的位置。
我有一个 URL,其中包含一个 JSON 文件,其中包含有关所有麦当劳餐厅的数据,我正在尝试在我的 Javascript 文件中读取它。
我试过了:
fetch("https://raw.githubusercontent.com/mmcloughlin/starbucks/master/locations.json")
.then(response =>response.json())
.then(json => showLocations(json));
但在浏览器控制台中出现此错误:
VM6256:1 Uncaught SyntaxError: Unexpected token < in JSON at position
0
at JSON.parse ()
at getObject (JSONFeature.js:202)
at GeoJSON2.JSONFeature2.readFeatures (JSONFeature.js:55)
at XMLHttpRequest.xhr.onload (featureloader.js:106)
我该如何解决?
您确定收到了 Json 文件吗?
如果是这样,请尝试将响应转换为字符串,然后将其解析为 JSON。
let resp = JSON.stringify(response);
res = JSON.parse(resp)
试试这个:
fetch("./data/test.json")
.then(response => {
if (response.status < 300) return response.json()
else // throw error or handle this case by giving the user an alert.
})
.then(json => showLocations(json));
这样你只会在收到 2XX
响应时才尝试解码 JSON
。
嘿,我找不到这个简单问题的答案。
我正在构建一个简单的 OpenLayers 项目。 作为项目的一部分,我想在地图上显示所有星巴克的位置。
我有一个 URL,其中包含一个 JSON 文件,其中包含有关所有麦当劳餐厅的数据,我正在尝试在我的 Javascript 文件中读取它。
我试过了:
fetch("https://raw.githubusercontent.com/mmcloughlin/starbucks/master/locations.json")
.then(response =>response.json())
.then(json => showLocations(json));
但在浏览器控制台中出现此错误:
VM6256:1 Uncaught SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse () at getObject (JSONFeature.js:202) at GeoJSON2.JSONFeature2.readFeatures (JSONFeature.js:55) at XMLHttpRequest.xhr.onload (featureloader.js:106)
我该如何解决?
您确定收到了 Json 文件吗?
如果是这样,请尝试将响应转换为字符串,然后将其解析为 JSON。
let resp = JSON.stringify(response);
res = JSON.parse(resp)
试试这个:
fetch("./data/test.json")
.then(response => {
if (response.status < 300) return response.json()
else // throw error or handle this case by giving the user an alert.
})
.then(json => showLocations(json));
这样你只会在收到 2XX
响应时才尝试解码 JSON
。