How to configure the Express response object to automatically add attributes to JSON?
Asked Answered
H

1

7

I have an object:

var obj = { "stuff": "stuff" }

In Express, I send it the client like so:

res.json(obj);

Is there a way to configure the response object to automatically add attributes to the json it generates? For example, to output:

{
  "status": "ok",
  "data": { "stuff": "stuff" }
}

Thanks!

Henson answered 1/2, 2013 at 22:17 Comment(0)
C
10

Once the data has been added to the stream, that's too late to rewrap it, so you have to do it before.

Either simply with a function:

res.json(wrap(obj));

You could also add your own json method

express.response.wrap_json = function(obj) {
  this.json(wrap(obj));
};

so you can now call

res.wrap_json(obj);

Or you could replace express json implementation with yours

var original = express.response.json;
express.response.json = function(obj) {
  original.call(this, wrap(obj));
};

I would only use the last one if you want to override all json calls.

Cupellation answered 2/2, 2013 at 1:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.