【问题标题】:Responding with a JSON object in Node.js (converting object/array to JSON string)在 Node.js 中响应 JSON 对象(将对象/数组转换为 JSON 字符串)
【发布时间】:2011-08-19 01:15:10
【问题描述】:

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

标签: javascript node.js


【解决方案1】:

res.json 与 Express 一起使用:

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

【讨论】:

    【解决方案2】:
    var objToJson = { };
    objToJson.response = response;
    response.write(JSON.stringify(objToJson));
    

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

    【讨论】:

    • 请注意 res.write(JSON.stringify()) 仍在等待您“结束”响应。 (重发()) ;为你表达 .json() 到这个
    【解决方案3】:

    您必须使用该节点使用的 V8 引擎附带的 JSON.stringify() 函数。

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

    编辑:据我所知,IANA 已在RFC4627 中正式为 JSON 注册了一个 MIME 类型为application/json。它也列在Internet Media Type 列表here 中。

    【讨论】:

    • 是否应该将 content-type 标头也设置为 application/json 或类似的东西?这方面的最佳做法是什么?
    • 是的,要使其成为客户能够理解的有效响应。添加:res.writeHead(200, {'Content-Type': 'application/json'}) 之前
    【解决方案4】:

    根据JamieLansweranother post

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

    例子:

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

    【讨论】:

    • 我怎样才能对 JSON 文件做同样的事情?
    • 不要忘记 res.end() 如果你使用这个,我需要它
    【解决方案5】:

    可能有应用程序范围的 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函数吗?我做对了吗?你为什么要这样做?只是好奇
    【解决方案6】:
    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);
    

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

    【讨论】:

      【解决方案7】:

      JSON.stringify() 方法将 JavaScript 对象或值转换为 JSON 字符串,如果指定了替换函数,则可选地替换值,或者如果指定了替换器数组,则可选地仅包括指定的属性。

      response.write(JSON.stringify({ x: 5, y: 6 }));
      

      know more

      【讨论】:

        猜你喜欢
        • 2022-11-19
        • 2013-07-14
        • 2021-06-12
        • 1970-01-01
        • 2013-08-29
        • 2012-05-08
        • 2011-05-21
        • 1970-01-01
        • 2014-11-11
        相关资源
        最近更新 更多