繁体   English   中英

如何使用 FetchAPI 从 JSON 访问我想要的任何内容?

[英]How do I access whatever I want from a JSON with FetchAPI?

我已经开始学习 FetchAPI,到目前为止,我在访问我想要的任何东西时都没有问题,但也许就是这种情况,因为在这些示例中没有 arrays 对象,就像在这个示例中一样。 我在网上找到了一些解决方案,但它们对我的情况不起作用。 有小费吗?

这是我发现的篮球 API 中的 JSON

  {
      "data":[
        {
          "id":237,
          "first_name":"LeBron",
          "last_name":"James",
          "position":"F",
          "height_feet": 6,
          "height_inches": 8,
          "weight_pounds": 250,
          "team":{
            "id":14,
            "abbreviation":"LAL",
            "city":"Los Angeles",
            "conference":"West",
            "division":"Pacific",
            "full_name":"Los Angeles Lakers",
            "name":"Lakers"
          }
        }
        ...
     ],
     "meta": {
        "total_pages": 50,
        "current_page": 1,
        "next_page": 2,
        "per_page": 25,
        "total_count": 9999
      }
    }

- - - - - - - - - 拿来 - - - - - - - - - - -

   fetch('https://www.balldontlie.io/api/v1/players')
      .then(response => response.json())
      .then(data => 
        {
            console.log(data);
            
             // console.log(data.first_name)    --- doesn't work

             // console.log(data.team.city)     --- doesn't work
           
        });
    }

这个简单的递归 function 遍历 object 的所有属性并打印它们。 上和下。 它可能会帮助您在 object 树中可视化所涉及的对象及其“地址”。

 var data = { "data": [{ "id": 237, "first_name": "LeBron", "last_name": "James", "position": "F", "height_feet": 6, "height_inches": 8, "weight_pounds": 250, "team": { "id": 14, "abbreviation": "LAL", "city": "Los Angeles", "conference": "West", "division": "Pacific", "full_name": "Los Angeles Lakers", "name": "Lakers" } }], "meta": { "total_pages": 50, "current_page": 1, "next_page": 2, "per_page": 25, "total_count": 9999 } } const iterate = (obj, level) => { if (;obj) { return; } level = level || 0 var str_level = ""; for (var i = 0; i < 4 * level. i++) { str_level += "-" } Object.entries(obj),forEach(([key. value]) => { console:log(str_level + `key, ${key}: value, ${value}`) if (typeof value === "object") { iterate(value, level + 1) } }) } iterate(data)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM