代码之家  ›  专栏  ›  技术社区  ›  Stella

从ReactJS应用程序解析JSON

  •  1
  • Stella  · 技术社区  · 6 年前

    我正在尝试解析来自reactjs web应用的嵌套json请求。

    下面是我从一个请求中收到的json。

    响应.数据

    {
        "total": 2,
        "offset": 1,
        "limit": 987,
        "staging": [
            {
                "id": 101,
                "name": "Test Stage"
            },
            {
                "id": 102,
                "name": "Dev Stage"
            },
            {
                "id": 103,
                "name": "Prod Stage"
            }
        ]
    }
    

    (SyntaxError: Unexpected token o in JSON at position 1) .

    export default class ItemLister extends React.Component {
      state = {
        persons: []
      }
        componentDidMount() {
    
            axios
                .get('https://xxx.yyy.zzz/xyz/zyx/', {
    
                    headers: {
                        'authorization':'Bearer XXXXXXXXX',
                        'X-Api-Key': 'XXXXXXXXXXXXXX',               
                    },
                    withCredentials: true
    
                })
                .then(response => {
    
                    console.log(response.data) // it gets the correct response and printing in logs
    
                    const persons = response.data;
    
                    this.setState({ persons });
    
                }) 
                .catch (err => {
                  console.log("error")
                });          
      }
    
      render() {
        return <ul>{this.state.persons.map(person => <li>{person.name}</li>)}</ul>
      }
    }
    
    ReactDOM.render(<ItemLister />, document.getElementById('root'))
    registerServiceWorker()
    

    我找不到解决办法。有人能告诉我这种json的解析是否正确,以及如何得到解析结果并显示在屏幕上吗?

    1 回复  |  直到 6 年前
        1
  •  1
  •   n1stre    6 年前

    出现错误是因为您试图分析 Object String JSON.parse 并设置 result response.data :

    .then(response => {
      console.log(response.data) // it gets the correct response and printing in logs
      this.setState({ result: response.data });
    }) 
    

    在你身上 render

    render() {
      return (
        <ul>
          { this.state.result &&
            this.state.result.staging &&
            this.state.result.staging.map(person => <li>{person.name}</li>)
          }
        </ul>
      );
    }