2

I am trying to parse a nested json request from my reactjs web app.

Below is the json that I received from a request.

response.data

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

I need to parse “staging” and display the results on browser screen.

Below is the code that I am trying to parse. But, it is throwing error (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()

I couldn't find fix for it. Can someone guide me whether the parsing of such json is correct or not and how to get the parsed results and displayed on screen?

2
  • 1
    Is staging really wrapped between backquote? Or normal quote? Commented Oct 30, 2018 at 15:47
  • Do you actually need to parse it as JSON? Is response.data already JSON? Commented Oct 30, 2018 at 15:51

1 Answer 1

1

An error occurs because you're trying to parse an Object instead of a String. Simply skip JSON.parse and set result to response.data:

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

And in you render:

render() {
  return (
    <ul>
      { this.state.result &&
        this.state.result.staging &&
        this.state.result.staging.map(person => <li>{person.name}</li>)
      }
    </ul>
  );
}
Sign up to request clarification or add additional context in comments.

2 Comments

Ok, this is not giving error now. But, not displaying on screen in the browser.
Ok sure. Yes Added now

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.