繁体   English   中英

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

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

我是后端代码的新手,我正在尝试创建一个函数来响应我的 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 字符串响应。 我需要放置不同的内容类型吗? 这个函数应该将该值传递给另一个在客户端说的吗?

谢谢你的帮助!

在 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);
}
var objToJson = { };
objToJson.response = response;
response.write(JSON.stringify(objToJson));

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

您必须使用 node 使用的 V8 引擎中包含的JSON.stringify()函数。

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

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

根据JamieL另一篇文章回答

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

例子:

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

在 express 中可能有应用程序范围的 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);
}
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);

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM