I have a REST API created using Node.JS and ExpressJS. I need to receive a JSON array from FrontEnd into my REST API.
api.post('/save_pg13_app_list', function (req, res) {
var app_list = {
list_object: req.body.list_object
};
console.log(app_list.list_object);
res.json({ type: "success", code: 200, data: app_list.list_object });
});
This list_object
is the JSON array I'm getting from the Front End.
This is the POST endpoint for the task.
http://localhost:7000/api/admin_control_manage/save_pg13_app_list
And this is the data object I'm receiving :
{
list_object : "[{name:\"chanaka\",\"code\":10},{name:\"shashini\",code:19}]"
}
When I'm taking this list_object
in my REST API , it's a String Object. Now I need to parse this to JSON. So I used following code to convert this to JSON.
var json_array = JSON.parse(app_list.list_object);
But I'm getting this error :
POST /api/admin_control_manage/save_pg13_app_list 500 0.936 ms - 1212 SyntaxError: Unexpected token n in JSON at position 2 at Object.parse (native) at /home/chanaka/WebstormProjects/PostureAPI/app/routes/admin_control.js:210:26 at Layer.handle [as handle_request] (/home/chanaka/WebstormProjects/PostureAPI/node_modules/express/lib/router/layer.js:95:5) at next (/home/chanaka/WebstormProjects/PostureAPI/node_modules/express/lib/router/route.js:131:13) at Route.dispatch (/home/chanaka/WebstormProjects/PostureAPI/node_modules/express/lib/router/route.js:112:3) at Layer.handle [as handle_request] (/home/chanaka/WebstormProjects/PostureAPI/node_modules/express/lib/router/layer.js:95:5) at /home/chanaka/WebstormProjects/PostureAPI/node_modules/express/lib/router/index.js:277:22 at Function.process_params (/home/chanaka/WebstormProjects/PostureAPI/node_modules/express/lib/router/index.js:330:12) at next (/home/chanaka/WebstormProjects/PostureAPI/node_modules/express/lib/router/index.js:271:10 ) at Function.handle (/home/chanaka/WebstormProjects/PostureAPI/node_modules/express/lib/router/index.js:176:3)
All I need to do is, convert [{name:"chanaka",code:10},{name:"shashini",code:19}]
kind of string array into JSON. What is the way to do this ?
Try stringifying the object in the callback function;
res.json({
type: "success",
code: 200,
data: JSON.stringify(app_list.list_object)
});
JSON stringify will format it correctly so it's gets properly parsed
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.