node and express send json formatted
Asked Answered
C

7

37

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?

Calcine answered 20/9, 2015 at 12:37 Comment(1)
JSON is always a string. To get the object back, you have to parse that string on the client side.Cwmbran
I
58

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));
  });
});
Interlock answered 20/9, 2015 at 12:40 Comment(1)
thanks it works with the stringify way. Please edit your post so it will be more clear and I can validate itCalcine
T
108

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.

Tournedos answered 2/1, 2018 at 14:25 Comment(6)
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!Rhamnaceous
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)Loam
Most convenient method and easy to turn on/off for dev/prod. Documentation: expressjs.com/en/4x/api.html#app.setChessboard
is there a way to make it coloured ?Hinda
@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 thisTournedos
well I meant from the server side itself. Can my Express app enforce colored json?Hinda
I
58

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));
  });
});
Interlock answered 20/9, 2015 at 12:40 Comment(1)
thanks it works with the stringify way. Please edit your post so it will be more clear and I can validate itCalcine
S
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');
  });
});
Shadrach answered 27/3, 2019 at 3:17 Comment(0)
C
1

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));
  });
});
Commutual answered 19/7, 2018 at 21:7 Comment(0)
H
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 .
Habanera answered 25/8, 2021 at 14:41 Comment(0)
J
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 })
Johnettajohnette answered 22/2, 2023 at 8:54 Comment(0)
C
-2

Maybe you need to JSON.parse(resp)

Contortionist answered 20/9, 2015 at 12:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.