Reputation: 357
I receive JSON by POST method in my router which I then return to the user. For some reason the returned JSON will have all numerical and boolean values casted to string. I am using koa-bodyparser if thats relevant.
Is there any way to avoid this?
Code:
var js = ctx.request.body.json;
ctx.body = {
status: 'success',
json: js
};
Input JSON:
{
"json": {
"numbers": 123
}
}
Output JSON:
{
"json": {
"numbers": "123"
}
}
Upvotes: 5
Views: 11305
Reputation: 89
Strict mode is already active by default (https://github.com/cojs/co-body#options) so you don't need to worry about it. This code works for me:
ctx.body = {
status: 'success',
json: ctx.request.body.json
};
I used Postman to send it to the koa server and received the answer in Postman which was:
{
"status": "success",
"json": {
"id": 1,
"name": "Joe"
}
}
As you can see the 'id' is a number. As you did not write about your client I assume it could be the browser? If so try to use the JSON.parse() function because you may get a string from your post-request. See this example:
JSON.parse("{\"json\":{\"id\":1}}");
You can also try Postman as client and see if that works (https://www.getpostman.com/).
Upvotes: 3