36

I'm trying to send formatted json with express.

Here is my code:

var app = express();

app.get('/', function (req, res) {
  users.find({}).toArray(function(err, results){
    // I have try both
    res.send(JSON.stringify(results, null, 4));
    // OR
    res.json(results);
  });
});

I get the json in my browser but it's a string. How can I send it so it's readable in the browser?

BoumTAC
  • 3,531
  • 6
  • 32
  • 44
  • 1
    JSON is always a string. To get the object back, you have to parse that string on the client side. – Sirko Sep 20 '15 at 12:40

7 Answers7

103

try to set the "secret" property json spaces on the Node app.

app.set('json spaces', 2)

This statement above will produce indentation on json content.

Alexis Diel
  • 1,246
  • 1
  • 9
  • 15
  • 2
    I think JSON.stringify() plus content-type header is the "official" way that one should understand, but this secret property is preferred because it's much cleverer! – Zhiyong Jul 11 '19 at 11:49
  • Definitely trick of the day ! Combined with `app.use(express.json())` it's much cleaner in code to have `res.json()` instead of `res.send(JSON.stringify(), null, 4)` – Oblx Jul 13 '22 at 19:06
  • Most convenient method and easy to turn on/off for dev/prod. Documentation: http://expressjs.com/en/4x/api.html#app.set – Ryan Sep 04 '22 at 14:13
  • is there a way to make it coloured ? – Lucifer Apr 24 '23 at 06:27
  • @Lucifer, for color, it depends on how you are consuming the endpoint, for example, if you use Google Chrome, you can install an extension to do this – Alexis Diel Apr 25 '23 at 12:09
  • well I meant from the server side itself. Can my Express app enforce colored json? – Lucifer Apr 26 '23 at 08:19
53

You're going to have to set the Content-Type to application/json like this

app.get('/', function (req, res) {
    users.find({}).toArray(function(err, results){
        res.header("Content-Type",'application/json');
        res.send(JSON.stringify(results, null, 4));
  });
});
Bidhan
  • 10,607
  • 3
  • 39
  • 50
  • thanks it works with the stringify way. Please edit your post so it will be more clear and I can validate it – BoumTAC Sep 20 '15 at 12:43
7

Use type('json') to set Content-Type and JSON.stringify() for formatting:

var app = express();

app.get('/', (req, res) => {
  users.find({}).toArray((err, results) => {
    res.type('json').send(JSON.stringify(results, null, 2) + '\n');
  });
});
Afanasii Kurakin
  • 3,330
  • 2
  • 24
  • 26
1

Sending JSON output as formatted from the server could be undesirable considering resource usage and performance of the server. Especially in production environments.

Instead, you can find a few ways to format the JSON output at client-side.

If you are using Chrome, you can use an extension among JSON Formatter, JSON Viewer, JSONView or others from Chrome web store.

Firefox provides built-in JSON viewer since Firefox 44.

When using curl or wget in a command line or a shell script, you can pipe the result in JSON into jq.

$ curl http://www.warehouse.com/products | jq .
Sangmoon Oh
  • 81
  • 1
  • 2
0

This should solve your problem

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

app.get('/', function (req, res) {
  users.find({}).toArray(function(err, results){
      res.json(JSON.parse(results));
  });
});
0

For convenience, you can override res.json in a custom middleware that runs before your routes.

To auto-format all JSON responses:

app.use('*', (req, res, next) => {
    res.json = (data) => res.type('json').send(JSON.stringify(data, null, 4))
    next()
})

app.get('/route', (req, res) => res.json({ formatted: true })

To allow custom formatting based on individual routes or other logic:

app.use('*', (req, res, next) => {
    res.json = (...args) => res.type('json').send(JSON.stringify(...args))
    next()
})

app.get('/tabs', (req, res) => res.json({ formatted: 'tabs' }, null, '\t')
app.get('/spaces', (req, res) => res.json({ formatted: 'spaces' }, null, 4)
app.get('/minified', (req, res) => res.json({ formatted: false })
Lionel Rowe
  • 5,164
  • 1
  • 14
  • 27
-2

Maybe you need to JSON.parse(resp)

Jason Livesay
  • 6,317
  • 3
  • 25
  • 31