JSON.解析URL



我有几个类似https://zkillboard.com/api/stats/solarSystemID/31000007/的URL我正试图从url中提取JSON到一个对象。

我已经能够得到到目前为止,它返回一个承诺,承诺:履行和承诺结果包含一个对象与我正在寻找的数据。

async function readJSON(url:string) {
var request = new XMLHttpRequest();
request.open ('get', url, false)
request.send(null)
if (request.status == 200) {
return JSON.parse(request.responseText)
}
}
const systemJSON = readJSON('https://zkillboard.com/api/stats/solarSystemID/31000007/')
console.log(systemJSON) 

我如何确保我的console.log只返回PromiseResult?

这似乎已经为我修复了它,从功能中删除了异步以及JSON.parse()中的.responseText

function readJSON(url:string) {
var request = new XMLHttpRequest();
request.open ('get', url, false)
request.send(null)
if (request.status == 200) {
return JSON.parse(request.response)
}
}

const systemJSON = readJSON('https://zkillboard.com/api/stats/solarSystemID/31000007/')

const printJSON = () =>{
console.log(systemJSON)
}
printJSON();

首先,当处理来自外部源的json时,我建议将其包装在try/catch函数中,以避免意外错误。

其次,我认为问题是readJSON返回一个承诺,所以你可能需要等待它。

try {
const json = await readJSON('https://zkillboard.com/api/stats/solarSystemID/31000007/')
const systemJSON = JSON.parse(json);
} catch (error) {
// Woops something happend - see error variable
}

最新更新