首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在Node.js中使用JSON对象进行响应(将对象/数组转换为JSON字符串)

在Node.js中使用JSON对象进行响应(将对象/数组转换为JSON字符串)
EN

Stack Overflow用户
提问于 2011-05-05 12:06:26
回答 5查看 247.2K关注 0票数 106

我是后端代码的新手,我正在尝试创建一个函数来响应我的JSON字符串。我现在有一个例子

代码语言:javascript
复制
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();
}

这基本上只是打印字符串"random numbers that should in the form of JSON“。我想要做的是用一个JSON字符串来响应任何数字。我需要放一个不同的内容类型吗?此函数是否应该将该值传递给客户端的另一个函数?

谢谢你的帮忙!

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2012-03-21 22:03:22

在Express中使用res.json

代码语言:javascript
复制
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"
  });
}

或者:

代码语言:javascript
复制
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);
}
票数 169
EN

Stack Overflow用户

发布于 2011-05-05 14:38:13

代码语言:javascript
复制
var objToJson = { };
objToJson.response = response;
response.write(JSON.stringify(objToJson));

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

票数 78
EN

Stack Overflow用户

发布于 2013-11-23 23:09:01

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

在研究了express\lib\response.js之后,我使用了以下例程:

代码语言:javascript
复制
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);
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5892569

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档