Reputation: 1868
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?
Upvotes: 2
Views: 91
Reputation: 6086
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>
);
}
Upvotes: 1