【问题标题】:Parsing an api response解析 api 响应
【发布时间】:2019-02-08 11:34:19
【问题描述】:

我想解析这个 api 响应以获取图像 url,实际上我发现它有点令人困惑,因为我是 api 新手。

    {
      "id": "123",
      "item": [
        {
          "picture": {
            "type_id": "2",
            "url": [
              "./img.jpg"
            ],
            "is_in_description": 0,
            "gallery": {
              "url": "",
              "url_id": ""
            },
            "layout_id": "2",
            "variation_name": ""
          },
          "lister_id": "12345"
        }
      ]
    }

这是我获取 api 的代码,有人可以帮我吗

fetch(url2,{
          method: 'GET'
        })
        .then((response)=> response.json())
        .then((responseJson) => {
          const newImg = responseJson.item.map( => {
            return{
              const img = 
            };
          })
          const newState = Object.assign({}, this.state, {
            items: newItems
          });

          console.log(newState);
          this.setState(newState);
        })
        .catch((error) => {
          console.log(error)
        });

【问题讨论】:

  • 你能详细说明一下什么解析响应。你可以通过解析直接访问item数组中每个元素的url属性

标签: reactjs rest api get fetch-api


【解决方案1】:

使用map方法解析为

var x =   {
      "id": "123",
      "item": [
        {
          "picture": {
            "type_id": "2",
            "url": [
              "./img.jpg"
            ],
            "is_in_description": 0,
            "gallery": {
              "url": "",
              "url_id": ""
            },
            "layout_id": "2",
            "variation_name": ""
          },
          "lister_id": "12345"
        }
      ]
    }

x.item.map(data=>{console.log(data.picture.url)}) //hope you need the url object

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-05
    • 2013-05-29
    • 2021-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多