我正在尝试访问JSON数据,但是JSON标识符使用多个单词。 JSON数据的格式如下:

    "Meta Data": {
        "1. Information": "Intraday (5min) open, high, low, close prices and volume",
        "2. Symbol": "IBM",
        "3. Last Refreshed": "2020-04-02 16:00:00",
        "4. Interval": "5min",
        "5. Output Size": "Compact",
        "6. Time Zone": "US/Eastern"
    },
    "Time Series (5min)": {
        "2020-04-02 16:00:00": {
            "1. open": "109.5600",
            "2. high": "110.3200",
            "3. low": "109.4300",
            "4. close": "110.0400",
            "5. volume": "421231"
        },
//...


我用:

componentDidMount() {
    fetch('https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=IBM&interval=5min&apikey=demo')
    .then(res => res.json())
    .then((data) => {
      this.setState({ StockInfo: data })
    })
    .catch(console.log)
  }


来获取数据。

console.log(StockInfo["Meta Data"])


该行可用于访问数据,但是

console.log(StockInfo["Meta Data"]["1. Information"]


我收到错误:TypeError:无法读取属性'1。信息'未定义。也,

console.log(StockInfo[0]) //or
console.log(StockInfo["Meta Data"][0]


也给出了相同的错误。

最佳答案

您将变得不确定,因为在componentDidMount之前以及在进行异步调用之前都会调用渲染函数。因此,在渲染中检查其是否可用。

 render() {
    if (!this.state.StockInfo["Meta Data"]) {
      return null;
    }
    return (
      <div>
         {this.state.StockInfo["Meta Data"]["1. Information"]}
      </div>
    );
  }


Stackblitz:https://stackblitz.com/edit/react-dnzze3

关于javascript - react 解析带有多个单词标识符的JSON数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/61018312/

10-11 19:24
查看更多