【问题标题】:How to select json data to display in html [duplicate]如何选择要在html中显示的json数据[重复]
【发布时间】:2020-07-20 11:00:18
【问题描述】:

我有这个 json 数据 URL,我只想选择法国数据以 html 显示,但我不知道该怎么做。请帮我这样做

https://coronavirus-19-api.herokuapp.com/countries

这是我的 JAVASCRIPT

// API Fetch Call
 const api_url = './src/india.json';
 async function getCcount() {
     const response = await fetch(api_url);
     const data = await response.json();
     const {
         cases,
         active,
         deaths,
         recovered
     } = data;

     document.getElementById('t-count').textContent = cases;
     document.getElementById('a-count').textContent = active;
     document.getElementById('d-count').textContent = deaths;
     document.getElementById('r-count').textContent = recovered;
 }

 getCcount();

如何仅选择法国数据以 HTML 格式显示。使用 fetch 函数。

【问题讨论】:

    标签: javascript html json api


    【解决方案1】:

    您必须find() data 数组中具有 country 属性和值为 "France" 的对象,如下所示:

    (async() => {
      try {
        const api_url = 'https://coronavirus-19-api.herokuapp.com/countries';
        const response = await fetch(api_url);
        if (response.status !== 200) {
          console.log(`Status Code: ${response.status}`);
          return;
        }
        const data = await response.json();
        const {
          cases,
          active,
          deaths,
          recovered
        } = data.find(covid => covid.country === 'France');
    
        document.getElementById('t-count').textContent = cases;
        document.getElementById('a-count').textContent = active;
        document.getElementById('d-count').textContent = deaths;
        document.getElementById('r-count').textContent = recovered;
      } catch (err) {
        console.log(`Fetch Error: ${err}`);
      }
    })();
    Cases: <span id='t-count'></span><br/> Active: <span id='a-count'></span><br/> Deaths: <span id='d-count'></span><br/> Recovered: <span id='r-count'></span><br/>

    find() 方法返回提供的数组中满足提供的测试功能的第一个元素的值。

    【讨论】:

      猜你喜欢
      • 2017-11-30
      • 2015-11-04
      • 1970-01-01
      • 2014-05-03
      • 1970-01-01
      • 2015-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多