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

cli*_*oid 92 javascript node.js

我是后端代码的新手,我正在尝试创建一个函数来响应我的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();
}
Run Code Online (Sandbox Code Playgroud)

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

谢谢你的帮助!

Kev*_*lly 153

在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"
  });
}
Run Code Online (Sandbox Code Playgroud)

或者:

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);
}
Run Code Online (Sandbox Code Playgroud)


dru*_*een 75

var objToJson = { };
objToJson.response = response;
response.write(JSON.stringify(objToJson));
Run Code Online (Sandbox Code Playgroud)

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


tyr*_*ter 21

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

var objToJson = { ... };
response.write(JSON.stringify(objToJson));
Run Code Online (Sandbox Code Playgroud)

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


Gre*_*reg 12

Per JamieL另一篇文章回答:

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

例:

res.json({"foo": "bar"});
Run Code Online (Sandbox Code Playgroud)