访问api子链接

时间:2018-05-22 22:54:00

标签: javascript api fetch

   componentDidMount = () => {
    fetch('https://api.teleport.org/api/urban_areas/?embed=ua:item/ua:images')
    .then(response => response.json())
    .then(data => {
      console.log(data)
      this.setState({
        images: data
      })
      console.log(this.state.images._embedded)
    })
  }

我目前是一名学生,负责从api读取数据并将其写入页面的项目。我试图找到这个api的一部分,我可以得到一些图像的URL。之前,我只使用了非常简单易用的api,并且总是使用点符号来获取数据及其内部部分。到目前为止,我使用点符号“data._embedded”得到了'_embedded'部分。但我无法弄清楚如何进入那个说'ua:item'的部分。我最终需要到“移动”部分才能获得图片网址。顺便说一下,这是一个React项目,如果它对这个特定问题有任何影响的话。非常感谢提前!

enter image description here

1 个答案:

答案 0 :(得分:0)

如果你有奇怪的东西,因为它们是JSON中的键值,你可以像这样使用方括号:

JSON.parse('{this:{is-a{JSON:"jsonstring"}}')["this"]["is-a"].JSON

产量:jsonstring

每当你得到只有一个项目的方括号(数组)时,索引为0,你可以再次使用数组表示法:[0]

在你的情况下:

 componentDidMount = () => {
    fetch('https://api.teleport.org/api/urban_areas/?embed=ua:item/ua:images')
        .then(response => response.json())
        .then(data => {
          console.log(data)
          this.setState({
            images: data
          })
          console.log(this._embedded["ua:item"][0]. _embedded["ua:item"].photos[0].image.mobile)
        })
      }