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


98

我是后端代码的新手,并且我正在尝试创建一个将响应我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();
}

基本上,这只是打印字符串“应该以JSON形式出现的随机数”。我要执行的操作是使用任何数字的JSON字符串进行响应。我需要放置其他内容类型吗?该函数应该将该值传递给客户端的另一个用户吗?

谢谢你的帮助!


res.json({“ Key”:“ Value”});
Amol M Kulkarni,2015年

Answers:


161

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

或者:

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

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

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


请注意res.write(JSON.stringify())仍在等待您“结束”响应。(重发()) ; 为您表达.json()
131年5

22

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

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

编辑:据我所知,IANA已经正式注册的MIME类型JSON作为application/jsonRFC4627。它也被列出的互联网媒体类型列表在这里


内容类型标头是否也应该设置为application / json或类似的名称?最佳做法是什么?
&”

1
是的,要使其成为有效的回应,客户会理解。添加:res.writeHead(200,{'Content-Type':'application / json'})之前
Ali


2

显然,可能存在应用程序范围的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);
}

这是用于发回JavaScript函数吗?我说对了吗?为什么要这么做?只是好奇
Sam Vloeberghs 2014-4-20

0
const http = require('http');
const url = require('url');

http.createServer((req,res)=>{

    const parseObj =  url.parse(req.url,true);
    const users = [{id:1,name:'soura'},{id:2,name:'soumya'}]

    if(parseObj.pathname == '/user-details' && req.method == "GET") {
        let Id = parseObj.query.id;
        let user_details = {};
        users.forEach((data,index)=>{
            if(data.id == Id){
                user_details = data;
            }
        })
        res.writeHead(200,{'x-auth-token':'Auth Token'})
        res.write(JSON.stringify(user_details)) // Json to String Convert
        res.end();
    }
}).listen(8000);

我在现有项目中使用了上面的代码。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.