【问题标题】:How to extract data from this API? HttpRequest, JavaScript如何从此 API 中提取数据? HttpRequest, JavaScript
【发布时间】:2021-08-28 12:30:37
【问题描述】:

如何提取数据?我需要赛道名称、日期、比赛名称、回合、季节和时间

var xhr = new XMLHttpRequest;

xhr.onreadystatechange = function(){
    if(this.readyState == 4 && this.status == 200){
  
        var json = JSON.parse(xhr.responseText);
        var yourData = json.MRData; 

 
        document.getElementById('playlist').innerHTML = yourData;

    }
};

xhr.open("GET", "http://ergast.com/api/f1/current/next.json", true);
xhr.send();

【问题讨论】:

标签: javascript api httprequest


【解决方案1】:

您可以使用.map 来使用比赛数组并为每个比赛返回一个遵循您的模型的对象:

var xhr = new XMLHttpRequest;

xhr.onreadystatechange = function(){
  if(this.readyState == 4 && this.status == 200){
  
    const json = JSON.parse(xhr.responseText);
    const { MRData: data } = json; 

    // show the json in HTML
    document.getElementById('playlist').innerHTML = JSON.stringify(data, null, 2);
    
    // log circuitName, date, raceName, round, season and time
    const { Races: races } = data.RaceTable
    
    const extractList = races.map(({ 
      Circuit: circuit, 
      date,
      raceName,
      round,
      season,
      time,
    }) => ({
      circuitName: circuit.circuitName,
      date,
      raceName,
      round,
      season,
      time,      
    }))
    console.log(extractList)

  }
};

xhr.open("GET", "http://ergast.com/api/f1/current/next.json", true);
xhr.send();
<pre id="playlist"></pre>

注意

要在 HTML 中呈现 JSON,您应该使用JSON.stringify 对对象进行字符串化,否则使用Object.prototype.toString 方法将其序列化为以下字符串:[Object object]

【讨论】:

  • “你必须 stringify 对象” - JSON.stringify() 与解决方案无关。 extractList的解释在哪里?
  • .map 的解释?我添加了一些文字来解释我做了什么。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-23
  • 1970-01-01
  • 2017-12-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多