15

I was exploring developing in Node.JS and found ExpressJS and RailwayJS (based on Express) which are frameworks for Node. The templating engine used Jade/EJS appears to be more for HTML. How might I generate JSON, eg. when I develop an API

Jiew Meng
  • 84,767
  • 185
  • 495
  • 805

2 Answers2

56

Express and Railway both extend off the HTTP module in node and both provide a "response" object as the second argument of the route/middleware handler's callback. This argument's name is usually shortened to res to save a few keystrokes.

To easily send an object as a JSON message, Express exposes the following method:

res.json({ some: "object literal" });

Examples:

app.use(function (req, res, next) {
  res.json({ some: "object literal" });
});

// -- OR -- //

app.get('/', function (req, res, next) {
  res.json({ some: "object literal" });
});

Check out the docs at expressjs.com and the github source is well documented as well

srquinn
  • 10,134
  • 2
  • 48
  • 54
11

You just create normal JavaScript objects, for example:

var x = {
    test: 1,
    embedded: {
        attr1: 'attr',
        attr2: false
    }
};

and

JSON.stringify(x);

turns it into JSON string. Note that x may contain functions which will be omitted. Also JSON.stringify returns x.toJSON() if .toJSON() is available.

freakish
  • 54,167
  • 9
  • 132
  • 169