1

I know you can configure Express to output either pretty JSON (app.set("json spaces", 2)) or minified JSON (app.set("json spaces", 0)), but is there a way to override this global setting on a particular response?

For example, if I set json spaces to 0, I could pretty print doing something like:

app.get("/foo", function(req,res) {
   res.json({"a":"b"}, 2);
});

Thanks!

3 Answers 3

6

Stringify wasn't working for me, for whatever reason. But setting json spaces did work.

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

app.get("*", async (request, response) => {
  ...
  response.json(m);
}

http://expressjs.com/en/api.html#app.set

Thank you to loganfsmyth for the tip.

Sign up to request clarification or add additional context in comments.

2 Comments

You don't need .type('application/json') if you're using .json().
Fixed. Thanks, @EtienneMartin.
1

A simple way to do it would be to use res.send and format the JSON on your own:

app.get("/foo", function(req,res) {
   res.send(JSON.stringify({"a":"b"}, null, 2));
});

MDN has more documentation on JSON.stringify

Comments

0

Thanks for the great answer wjohnsto! Building off of your answer, and digging around in the response.js code, I had to make one modification to get it to work properly:

app.get("/foo", function(req, res) {
   res
     .set("Content-type", "application/json; charset=utf-8")
     .send(JSON.stringify({"a":"b"}, null, 2));
});

I ended up creating a function sendPretty(res, data) for reusability.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.