无法使用Fetch访问JSON元素

huangapple go评论67阅读模式
英文:

Can't access json element using Fetch

问题

我试图获取一个 JSON 文件并在一个 div 中显示其元素。

这是我的 JSON 数据:

这是我的代码。第一部分获取 JSON 数据。第二部分应该在一个 div 中显示这两个元素(这里我只是打印结果):

如何返回所有的 host_id?
英文:

I'm trying to fetch a json file and display its elements in a div.

This is my json data :

[
    {
       "0":{
          "host_id":"129230780",
          "host_names":"STK Homes",
          "host_since":"2017-05-07T12:45:49Z",
          "nb_listings":"2128",
          "langues":"['English']",
          "localisation":"Londres, Royaume-Uni",
          "is_superhost":"False",
          "is_viewer_profile_owner":"False",
          "reviews_count":"1228",
          "url":"https://fr.airbnb.ca/users/show/129230780"
       },
       "1":{
          "host_id":"121683635",
          "host_names":"Evolve",
          "host_since":"2017-03-20T16:26:31Z",
          "nb_listings":"700",
          "langues":"['English', 'Espa\u00f1ol', 'Fran\u00e7ais']",
          "localisation":"\u00c9tats-Unis",
          "is_superhost":"False",
          "is_viewer_profile_owner":"False",
          "reviews_count":"16495",
          "url":"https://fr.airbnb.ca/users/show/121683635"
       }
    }
]

This is my code. The first part fetches the json data. The second part is supposed to display the two elements in a div (here I'm just printing the results):

 fetch(json object)
        .then(function (response) {
          return response.json(); 
      })
        .then(function (data) {
          appendData(data);
      })
        .catch(function (err) {
        console.log(err);
      });

   
      function appendData(data) {
        for (var i = 0; i < data.length; i++) {
          console.log(data[0][i].host_id) // return just the first host_id
          console.log(data[i][i].host_id) // also return just the first host_id
        }
      } 

How could I return all the host ids ?

答案1

得分: 1

为了从JSON数据中返回所有的主机ID,你可以修改appendData函数,循环遍历数组中的每个对象,然后循环遍历对象中的每个键,以获取host_id的值。

function appendData(data) {
  for (var i = 0; i < data.length; i++) {
    var obj = data[i];
    for (var key in obj) {
      var host_id = obj[key].host_id;
      console.log(host_id);
      // 你可以将host_id附加到一个`div`元素而不是记录到控制台
    }
  }
}
英文:

to To return all the host ids from the JSON data, you can modify the appendData function to loop through each object in the array and then loop through each key in the object to get the host_id value.

function appendData(data) {
  for (var i = 0; i &lt; data.length; i++) {
    var obj = data[i];
    for (var key in obj) {
      var host_id = obj[key].host_id;
      console.log(host_id);
      // You can append the host_id to a div element instead of logging to the console
    }
  }
}

答案2

得分: 1

以下是翻译好的代码部分:

function main() {
  fetch('...')
    .then(function(response) {
      return response.json();
    })
    .then(function(data) {
      appendData(data);  // 场景 #1
      appendData2(data); // 场景 #2
    })
    .catch(function(err) {
      console.log(err);
    });
}

// 属性解构 + for-in 循环
function appendData(data) {
  const [hostsObj] = data;
  for (let key in hostsObj) {
    const { host_id } = hostsObj[key];
    console.log(host_id);
  }
}

// 内联属性解构 + Object.values + forEach
function appendData2([hostsObj]) {
  Object.values(hostsObj).forEach(({ host_id }) => {
    console.log(host_id);
  });
}

// 仅供测试:覆盖/模拟默认的 Fetch API
window.fetch = () => Promise.resolve({
  json: () => Promise.resolve([{
    "0": {
      "host_id": "129230780",
      "host_names": "STK Homes",
      "host_since": "2017-05-07T12:45:49Z",
      "nb_listings": "2128",
      "langues": "['English']",
      "localisation": "Londres, Royaume-Uni",
      "is_superhost": "False",
      "is_viewer_profile_owner": "False",
      "reviews_count": "1228",
      "url": "https://fr.airbnb.ca/users/show/129230780"
    },
    "1": {
      "host_id": "121683635",
      "host_names": "Evolve",
      "host_since": "2017-03-20T16:26:31Z",
      "nb_listings": "700",
      "langues": "['English', 'Español', 'Français']",
      "localisation": "États-Unis",
      "is_superhost": "False",
      "is_viewer_profile_owner": "False",
      "reviews_count": "16495",
      "url": "https://fr.airbnb.ca/users/show/121683635"
    }
  }])
});

main();
.as-console-wrapper { top: 0; max-height: 100% !important; }
英文:

There's are more than one way to loop over an object wrapped inside of an array.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

function main() {
fetch(&#39;...&#39;)
.then(function(response) {
return response.json();
})
.then(function(data) {
appendData(data);  // Scenario #1
appendData2(data); // Scenario #2
})
.catch(function(err) {
console.log(err);
});
}
// Prop destructure + for-in loop
function appendData(data) {
const [hostsObj] = data;
for (let key in hostsObj) {
const { host_id } = hostsObj[key];
console.log(host_id);
}
}
// Inline prop destructure + Object.values + forEach
function appendData2([hostsObj]) {
Object.values(hostsObj).forEach(({ host_id }) =&gt; {
console.log(host_id);
});
}
// TEST ONLY :- Override / mock the default Fetch API
window.fetch = () =&gt; Promise.resolve({
json: () =&gt; Promise.resolve([{
&quot;0&quot;: {
&quot;host_id&quot;: &quot;129230780&quot;,
&quot;host_names&quot;: &quot;STK Homes&quot;,
&quot;host_since&quot;: &quot;2017-05-07T12:45:49Z&quot;,
&quot;nb_listings&quot;: &quot;2128&quot;,
&quot;langues&quot;: &quot;[&#39;English&#39;]&quot;,
&quot;localisation&quot;: &quot;Londres, Royaume-Uni&quot;,
&quot;is_superhost&quot;: &quot;False&quot;,
&quot;is_viewer_profile_owner&quot;: &quot;False&quot;,
&quot;reviews_count&quot;: &quot;1228&quot;,
&quot;url&quot;: &quot;https://fr.airbnb.ca/users/show/129230780&quot;
},
&quot;1&quot;: {
&quot;host_id&quot;: &quot;121683635&quot;,
&quot;host_names&quot;: &quot;Evolve&quot;,
&quot;host_since&quot;: &quot;2017-03-20T16:26:31Z&quot;,
&quot;nb_listings&quot;: &quot;700&quot;,
&quot;langues&quot;: &quot;[&#39;English&#39;, &#39;Espa\u00f1ol&#39;, &#39;Fran\u00e7ais&#39;]&quot;,
&quot;localisation&quot;: &quot;\u00c9tats-Unis&quot;,
&quot;is_superhost&quot;: &quot;False&quot;,
&quot;is_viewer_profile_owner&quot;: &quot;False&quot;,
&quot;reviews_count&quot;: &quot;16495&quot;,
&quot;url&quot;: &quot;https://fr.airbnb.ca/users/show/121683635&quot;
}
}])
});
main();

<!-- language: lang-css -->

.as-console-wrapper { top: 0; max-height: 100% !important; }

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年3月7日 02:32:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/75654564.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定