22

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
  • 2,675
  • 3
  • 21
  • 37
  • 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

5 Answers5

57

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
  • 775
  • 6
  • 15
  • 1
    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
41

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,089
  • 3
  • 34
  • 46
  • 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
4

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
  • 2,766
  • 2
  • 20
  • 21
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));
  });
});
-1

Maybe you need to JSON.parse(resp)

Jason Livesay
  • 6,116
  • 3
  • 22
  • 30