Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I generate JSON with ExpressJS/RailwayJS (Node.JS)

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

like image 573
Jiew Meng Avatar asked May 19 '12 13:05

Jiew Meng


People also ask

Does Express automatically parse JSON?

Express doesn't automatically parse the HTTP request body for you, but it does have an officially supported middleware package for parsing HTTP request bodies. As of v4. 16.0, Express comes with a built-in JSON request body parsing middleware that's good enough for most JavaScript apps.

What is Express JSON in node JS?

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.


2 Answers

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.

like image 22
freakish Avatar answered Nov 15 '22 14:11

freakish


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

like image 112
srquinn Avatar answered Nov 15 '22 14:11

srquinn