如何访问此api响应中嵌套的城市名称?

时间:2018-12-20 12:51:11

标签: json reactjs object

我使用axios.get(...)请求数据,成功获得作为嵌套对象的返回。我可以访问data.message,data.cnt,data.cod,但无法访问“ city”的属性。不断变得不确定或输入错误。

我想访问嵌套在响应数据中的city对象的属性。像这样的“ data.city.name”,但会出错。

{
  "cod": "200",
  "message": 0.0051,
  "cnt": 40,
  "list": [
    {
      "dt": 1545318000,
      "main": {
        "temp": 282.74,
        "temp_min": 282.167,
        "temp_max": 282.74,
        "pressure": 1012.86,
        "sea_level": 1020.54,
        "grnd_level": 1012.86,
        "humidity": 84,
        "temp_kf": 0.57
      },
      "weather": [
        {
          "id": 500,
          "main": "Rain",
          "description": "light rain",
          "icon": "10d"
        }
      ],
      "clouds": { "all": 44 },
      "wind": { "speed": 5.67, "deg": 243.503 },
      "rain": { "3h": 0.25 },
      "sys": { "pod": "d" },
      "dt_txt": "2018-12-20 15:00:00"
    },
    {
      "dt": 1545739200,
      "main": {
        "temp": 282.628,
        "temp_min": 282.628,
        "temp_max": 282.628,
        "pressure": 1037.58,
        "sea_level": 1045.29,
        "grnd_level": 1037.58,
        "humidity": 100,
        "temp_kf": 0
      },
      "weather": [
        {
          "id": 500,
          "main": "Rain",
          "description": "light rain",
          "icon": "10d"
        }
      ],
      "clouds": { "all": 76 },
      "wind": { "speed": 2.02, "deg": 212.503 },
      "rain": { "3h": 0.13 },
      "sys": { "pod": "d" },
      "dt_txt": "2018-12-25 12:00:00"
    }
  ],
  "city": {
    "id": 2643743,
    "name": "London",
    "coord": { "lat": 51.5073, "lon": -0.1277 },
    "country": "GB",
    "population": 1000000
  }
}

5 个答案:

答案 0 :(得分:1)

使用JSON.parse();

示例:

var data = JSON.parse(yourJSONObject)
console.log(data.city.name)

答案 1 :(得分:1)

可能无法完全代表您的需求,但这应该说明如何设置默认状态,获取结果,然后将其传递给组件。您的对象很好,我觉得您可能在Axios完成之前尝试访问它。

export class DataView extends Component {
    constructor(props) {
      super(props);
      this.state = {
        isLoading: true,
        data: {}
      };
      this.defaultState = {
         // default properties of state 
      };
    }

    componentWillMount() {
      this.fetchData();
    }

    fetchData = () => {
        await axios.get( ${apiEndpoint}${inputCity}&appid=${apiKey} )
        .then( data => {
            this.setState({
              data,
              ...this.defaultState,
              isLoading: false
            });
        });
    };


    render() {
      return (
        <Fragment>
          {this.state.isLoading ? ( // Check if it's still loading and load nothing if true
            <Fragment />
          ) : (
            <Component withProps={this.state.data}></Component> // Data can be accessed if isLoading: false
          )}
        </Fragment>
      );
    }
  }

答案 2 :(得分:0)

如果您正在获取data.message,则必须使用data.city.name获取城市名称

答案 3 :(得分:0)

我认为您的代码中存在一些错误,因为我可以访问数据并且json也有效。

尝试console.log()响应,看看发生了什么。

答案 4 :(得分:0)

Seems to work fine with data.city.name

const data = {
  "cod": "200",
  "message": 0.0051,
  "cnt": 40,
  "list": [
    {
      "dt": 1545318000,
      "main": {
        "temp": 282.74,
        "temp_min": 282.167,
        "temp_max": 282.74,
        "pressure": 1012.86,
        "sea_level": 1020.54,
        "grnd_level": 1012.86,
        "humidity": 84,
        "temp_kf": 0.57
      },
      "weather": [
        {
          "id": 500,
          "main": "Rain",
          "description": "light rain",
          "icon": "10d"
        }
      ],
      "clouds": { "all": 44 },
      "wind": { "speed": 5.67, "deg": 243.503 },
      "rain": { "3h": 0.25 },
      "sys": { "pod": "d" },
      "dt_txt": "2018-12-20 15:00:00"
    },
    {
      "dt": 1545739200,
      "main": {
        "temp": 282.628,
        "temp_min": 282.628,
        "temp_max": 282.628,
        "pressure": 1037.58,
        "sea_level": 1045.29,
        "grnd_level": 1037.58,
        "humidity": 100,
        "temp_kf": 0
      },
      "weather": [
        {
          "id": 500,
          "main": "Rain",
          "description": "light rain",
          "icon": "10d"
        }
      ],
      "clouds": { "all": 76 },
      "wind": { "speed": 2.02, "deg": 212.503 },
      "rain": { "3h": 0.13 },
      "sys": { "pod": "d" },
      "dt_txt": "2018-12-25 12:00:00"
    }
  ],
  "city": {
    "id": 2643743,
    "name": "London",
    "coord": { "lat": 51.5073, "lon": -0.1277 },
    "country": "GB",
    "population": 1000000
  }
}

document.write(data.city.name);

getData = async () => {
  const { inputCity } = this.state;

  try {
    const data = await axios.get(${apiEndpoint}${inputCity}&appid=${apiKey});
    this.setState({ data });
    console.log(this.state.data);
    return data;
  } catch (err) {
    console.error(err);
  }
}