在NodeJS中响应一个JSON对象(将对象/数组转换为JSONstring)

我是一个新手到后端代码,我试图创build一个函数,将响应我一个JSONstring。 我现在有一个例子

function random(response) { console.log("Request handler 'random was called."); response.writeHead(200, {"Content-Type": "text/html"}); response.write("random numbers that should come in the form of json"); response.end(); } 

这基本上只是打印string“应该以json的forms来的随机数”。 我想要做的是用一个数字的jsonstring来回应。 我是否需要放置不同的内容types? 这个函数应该把这个值传给另一个在客户端上说的吗?

谢谢你的帮助!

使用res.json :

 function random(response) { console.log("response.json sets the appropriate header and performs JSON.stringify"); response.json({ anObject: { item1: "item1val", item2: "item2val" }, anArray: ["item1", "item2"], another: "item" }); } 

或者:

 function random(response) { console.log("Request handler random was called."); response.writeHead(200, {"Content-Type": "application/json"}); var otherArray = ["item1", "item2"]; var otherObject = { item1: "item1val", item2: "item2val" }; var json = JSON.stringify({ anObject: otherObject, anArray: otherArray, another: "item" }); response.end(json); } 
 var objToJson = { }; objToJson.response = response; response.write(JSON.stringify(objToJson)); 

如果你alert(JSON.stringify(objToJson))你会得到{"response":"value"}

您必须使用节点使用的V8引擎中包含的JSON.stringify()函数。

 var objToJson = { ... }; response.write(JSON.stringify(objToJson)); 

编辑:据我所知, IANA在RFC4627中正式注册了JSON的MIMEtypes作为application/json 。 这里也列出了Internet Media Type列表。

Per JamieL对另一篇文章的回答 :

由于Express.js 3x的响应对象有一个json()方法为您正确设置所有的标题。

例:

 res.json({"foo": "bar"}); 

在express中可能有应用程序范围的JSON格式器。

看了express \ lib \ response.js之后,我正在使用这个例程:

 function writeJsonPToRes(app, req, res, obj) { var replacer = app.get('json replacer'); var spaces = app.get('json spaces'); res.set('Content-Type', 'application/json'); var partOfResponse = JSON.stringify(obj, replacer, spaces) .replace(/\u2028/g, '\\u2028') .replace(/\u2029/g, '\\u2029'); var callback = req.query[app.get('jsonp callback name')]; if (callback) { if (Array.isArray(callback)) callback = callback[0]; res.set('Content-Type', 'text/javascript'); var cb = callback.replace(/[^\[\]\w$.]/g, ''); partOfResponse = 'typeof ' + cb + ' === \'function\' && ' + cb + '(' + partOfResponse + ');\n'; } res.write(partOfResponse); }