0
votes

I use express in my node App to send a JSON response:

App.get('/shops', function (req, res) {
    res.json(200, {
        success: true,
        reason: 'data found correctly',
        shops: shops
    });
}

If in Chrome I go to 127.0.0.1:port/shops I see the response as a string (all in one line); is it possible to send the JSON answer formatted?

Before (with a less recent version of express) I was using something like

answer = JSON.stringify(answer, null, '\t');   // answer is a js object
res.send(200, answer);

But now (with express 4) even if I try something like that I see in the browser one row with many \n and \t inside of it;

Don't know if it is due to express version...

1
Is this a new build/project? If so, why aren't you leveraging Express 4?leaksterrr
yes, sorry I'm using express 4.4.4; it has been an error ;)Cereal Killer

1 Answers

1
votes

The json spaces setting sets the indent character for JSON output. To enable pretty printing, do the following to your application:

var app = express();
app.set('json spaces', '  ');
// ...

As of 2014-06-24, this is not currently documented in the Express 4 API, but the behaviour can be found in the source code for res.json:

var spaces = app.get('json spaces');
var body = JSON.stringify(obj, replacer, spaces);