Jipin Gopi Jipin Gopi - 4 months ago 12
Node.js Question

Escape character inserted '\' while returning json from api node.js

I'm trying to create on simple api using node.js
Here is the code`var express=require("express");

var app =express();

var fs=require("fs")
var bodyParser = require('body-parser');

app.use(express.static('public'));



var router = express.Router();
var port = process.env.PORT || 8081;
//Read file from JSON file


router.get('/', function(req, res) {

fs.readFile('routes.JSON','utf8',function (err,data) {
if(err){
console.log(err);
}
console.log(data);
res.json(data);
});


});

app.use('/api', router);


app.listen(port);
console.log('Listening to ' + port);`

Here I'm reading a json file routes.JSON and return the value to http://127.0.0.1:8081/api

I'm expecting the output `
{
"placeid": 123,
"timings": {
"time":"12/03/2014:09:12",
"geocode": {
"long":"37.423021",
"lat":"122.083739",
"toLocation":"Vaikom"
}

}

}`


But it gives the output like this

"{\r\n \"placeid\": 123,\r\n \"timings\": {\r\n \"time\":\"12/03/2014:09:12\",\r\n \"geocode\": {\r\n \"long\":\"37.423021\",\r\n \"lat\":\"122.083739\",\r\n \"toLocation\":\"Chempu\"\r\n }\r\n \r\n }\r\n \r\n}"

I was able to write json to console without '\'.

Answer

Add JSON.parse function when you return data like this.

res.json(JSON.parse(data));

When you are reading from file its basically of string datatype. When you output to the console its prints whatever was in file giving you an illusion that its a json object but its string. Try printing typeof data also to console, you would understand.