Javascript 在 Node.js 中响应 JSON 对象(将对象/数组转换为 JSON 字符串)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5892569/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:23:52  来源:igfitidea点击:

Responding with a JSON object in Node.js (converting object/array to JSON string)

javascriptnode.js

提问by climboid

I'm a newb to back-end code and I'm trying to create a function that will respond to me a JSON string. I currently have this from an example

我是后端代码的新手,我正在尝试创建一个函数来响应我的 JSON 字符串。我目前从一个例子中得到这个

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();
}

This basically just prints the string "random numbers that should come in the form of JSON". What I want this to do is respond with a JSON string of whatever numbers. Do I need to put a different content-type? should this function pass that value to another one say on the client side?

这基本上只是打印字符串“应该以 JSON 形式出现的随机数”。我想要做的是用任何数字的 JSON 字符串响应。我需要放置不同的内容类型吗?这个函数应该将该值传递给另一个在客户端说的吗?

Thanks for your help!

谢谢你的帮助!

回答by Kevin Reilly

Using res.jsonwith Express:

在 Express 中使用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"
  });
}

Alternatively:

或者:

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);
}

回答by druveen

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

If you alert(JSON.stringify(objToJson))you will get {"response":"value"}

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

回答by tyronegcarter

You have to use the JSON.stringify()function included with the V8 engine that node uses.

您必须使用JSON.stringify()node 使用的 V8 引擎附带的功能。

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

Edit:As far as I know, IANAhas officially registered a MIME type for JSON as application/jsonin RFC4627. It is also is listed in the Internet Media Typelist here.

编辑:据我所知,IANA已经正式注册的MIME类型JSON作为application/jsonRFC4627。它也列在此处Internet 媒体类型列表中。

回答by Greg

Per JamieL's answerto another post:

根据JamieL另一篇文章回答

Since Express.js 3x the response object has a json() method which sets all the headers correctly for you.

Example:

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

从 Express.js 3x 开始,响应对象有一个 json() 方法,可以为您正确设置所有标头。

例子:

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

回答by Amir Arad

in express there may be application-scoped JSON formatters.

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

after looking at express\lib\response.js, I'm using this routine:

查看 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);
}