如何使用ExpressJS / RailwayJS(Node.JS)生成JSON

时间:2022-11-25 14:23:07

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

我正在探索Node.JS的开发,发现ExpressJS和RailwayJS(基于Express)是Node的框架。使用Jade / EJS的模板引擎似乎更适合HTML。我怎样才能生成JSON,例如。当我开发API时

2 个解决方案

#1


11  

You just create normal JavaScript objects, for example:

您只需创建普通的JavaScript对象,例如:

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.

把它变成JSON字符串。请注意,x可能包含将被省略的函数。如果.toJSON()可用,JSON.stringify也会返回x.toJSON()。

#2


55  

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.

Express和Railway都延伸到节点中的HTTP模块,并且都提供“响应”对象作为路由/中间件处理程序的回调的第二个参数。此参数的名称通常缩短为res以保存一些键击。

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

为了轻松地将对象作为JSON消息发送,Express公开了以下方法:

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

查看expressjs.com上的文档,github源代码也有详细记录

#1


11  

You just create normal JavaScript objects, for example:

您只需创建普通的JavaScript对象,例如:

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.

把它变成JSON字符串。请注意,x可能包含将被省略的函数。如果.toJSON()可用,JSON.stringify也会返回x.toJSON()。

#2


55  

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.

Express和Railway都延伸到节点中的HTTP模块,并且都提供“响应”对象作为路由/中间件处理程序的回调的第二个参数。此参数的名称通常缩短为res以保存一些键击。

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

为了轻松地将对象作为JSON消息发送,Express公开了以下方法:

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

查看expressjs.com上的文档,github源代码也有详细记录