node.jsexpresspugejsrailway.js

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


Solution

  • 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.