访问深层嵌套的API JSON对象(React JS)

时间:2020-07-06 20:23:32

标签: json reactjs

我正在尝试使用Openweather API创建天气应用。我能够成功检索JSON对象,但是在遍历该对象时遇到了麻烦,我想访问特定日期和时间的天气详细信息,但是我一生都无法将这个概念全神贯注。有时候我可以访问JSON对象的名称,但是当我尝试从特定的日期和时间访问特定的天气详细信息时,经常遇到错误。其中一些信息是如此之深,以至于我不确定如何检索信息

    fetch(`https://api.openweathermap.org/data/2.5/forecast?zip=${zip}&units=imperial&appid=5672e526c1cbc8d71aed230e5e151426`)
      .then(response => response.json())
      .then(json => {
        console.log(json.list);
      });
  }, [apiSearch]);

如果我只是尝试在json.list的末尾添加索引:

        console.log(json.list[1]);

我有时会遇到诸如无法将未定义或null转换为对象之类的错误,或者类似的错误,我想知道访问下面的对象数组及其所有信息的最佳方法,谢谢!

Openweather api nested JSON object called by json.list

我尝试了多种方法,包括Object.keys,映射等,但是我总是碰到一个对象是null错误或某种错误。我想遍历40个数组,可以说访问温度,每次尝试都导致我失败。任何帮助将不胜感激,谢谢!

2 个答案:

答案 0 :(得分:2)

希望这会对您有所帮助。

fetch(`https://api.openweathermap.org/data/2.5/forecast?zip=99501&units=imperial&appid=5672e526c1cbc8d71aed230e5e151426`)
      .then(response => response.json())
      .then(json => {
        const forcasetList = json.list;
        forcasetList.forEach(f => {
          console.log(f.main.temp)
        })
      });

答案 1 :(得分:1)

这里可能有几个问题:

获取和响应状态

由于您使用的是fetch,因此返回的响应可能并不总是有效的响应,因此应首先检查您是否拥有HTTP 200状态响应,例如:

fetch(url).then(
  response => {
    if (response.status !== 200) {
      throw new Error(`Expected status 200 ok got status: ${response.status}`)
    }

    return response.json()
  }
).then(...)

不正确/无效数据

我不熟悉openweathermap API,但从我在API中看到的情况来看,forecast list应该始终具有完整的非null对象。

但是您可以通过以下方式添加一些验证或防护措施:

  1. 使用AVJ之类的JSON模式验证
  2. 或者具有一个分析方法,该方法检查列表并返回非null元素
fetch(url).then(
  response => {
    if (response.status !== 200) {
      throw new Error(`Expected status 200 ok got status: ${response.status}`)
    }

    return response.json()
  }
).then(
  forecast => {
    // here you could validate using something like AVJ to
    // check that the json response is valid
    if (!valid(forecast)) {
      throw new Error('Invalid forecast data')
    }

    // Some custom filtering and validation example
    const list = forecast.list || []
    return list.filter(
      item => {
        // filter out null objects
        if (!item) {
          return false
        }
        
        // other validations.
        ...

        // validate the date is within your range
        if (item.dt ...) {
          return false
        }
        
        // valid item
        return true
      }
    )
    .map (
      // extract the weather part
      item => item.weather
    )
  }
).then(
  weatherItems => {
    // work with weather items here
  } 
)