Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Express.Js output minified JSON?

I'm currently switching from restified to Express, and I noticed that the output of res.send({}) in Express has pretty-printed JSON with white space, while the Restify output is minified without white space.

Since the JSON is not for human consumption, I prefer the minified output. Is there an easy way to get Express to output minified JSON without individually changing all the res.send() calls? I would also prefer a setting over adding more middle-ware for performance reasons.

like image 955
Killroy Avatar asked Nov 07 '13 10:11

Killroy


People also ask

How do I prettify JSON in node JS?

If you just want to pretty print an object and not export it as valid JSON you can use console. dir() . It uses syntax-highlighting, smart indentation, removes quotes from keys and just makes the output as pretty as it gets. Under the hood it is a shortcut for console.

Does Express use JSON?

json() is a built-in middleware function in Express. This method is used to parse the incoming requests with JSON payloads and is based upon the bodyparser. This method returns the middleware that only parses JSON and only looks at the requests where the content-type header matches the type option.

How do you minify JSON?

To minify json string, first we will convert it to an Object by using JSON. parse() method, then we will use JSON. stringify() method to minify it by passing space ( o ) as an argument.


1 Answers

You can set the json spaces setting to 0:

var app = express();

app.set('json spaces', 0);

Express will do that automatically when you run it in production mode, though:

NODE_ENV=production node app
like image 200
robertklep Avatar answered Oct 05 '22 11:10

robertklep