I have written an API that outputs JSON in the following format:
{
"status": true,
"data": [
{
"id": 10,
"name": "The Land Before Time",
"genre": "Fantasy",
"rating": 7,
"explicit": false
},
{
"id": 11,
"name": "Jurassic Park",
"genre": "Science Fiction",
"rating": 9,
"explicit": true
},
{
"id": 14,
"name": "Ice Age 3: Dawn of the Dinosaurs",
"genre": "Action/Romance",
"rating": 2,
"explicit": false
}
]
}
But I can't figure out how to process json before issuing it to the React component state.
Tell me some discussions or materials, articles that will help me understand "how to properly process data from json that the API has issued, regardless of the use of objects and/or arrays or nesting levels. Maybe there is a library for these purposes?
I will be grateful for your help.
CodePudding user response:
If you are using axios
it should parse the JSON after the request, you just save the result in a variable and you can get all the data from there.
BTW don't forget axios
returns a promise so use await
or then
to handle it.
CodePudding user response:
I think you don't need any libraries. You can just use JSON.parse()
.
The response of API would be string type. So you first parse it and you can get an JSON object. And you can handle it as your need to set React state.