Jipin Gopi Jipin Gopi - 1 year ago 58
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');


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) {


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

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

Here I'm reading a json file routes.JSON and return the value to

I'm expecting the output `
"placeid": 123,
"timings": {
"geocode": {



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 Source

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


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download