【问题标题】:JSON.parse from a URL来自 URL 的 JSON.parse
【发布时间】:2021-02-22 19:38:07
【问题描述】:

我有几个类似于https://zkillboard.com/api/stats/solarSystemID/31000007/ 的网址 我正在尝试将 url 中的 JSON 提取到一个对象中。

我已经能够做到这一点,它返回一个 Promise,PromiseState:fulfilled 并且 PromiseResults 包含一个包含我正在寻找的数据的对象。

  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 reactjs


    【解决方案1】:

    这似乎为我修复了它,从函数中删除了异步以及 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();
    

    【讨论】:

      【解决方案2】:

      首先,在处理来自外部源的 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
      }
      

      【讨论】:

        猜你喜欢
        • 2019-01-01
        • 2019-04-03
        • 2016-05-18
        • 1970-01-01
        • 1970-01-01
        • 2023-03-21
        • 1970-01-01
        • 2011-10-09
        • 1970-01-01
        相关资源
        最近更新 更多