简体   繁体   English

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

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

I'm a newb to back-end code and I'm trying to create a function that will respond to me a JSON string.我是后端代码的新手,我正在尝试创建一个函数来响应我的 JSON 字符串。 I currently have this from an example我目前从一个例子中得到这个

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".这基本上只是打印字符串“应该以 JSON 形式出现的随机数”。 What I want this to do is respond with a JSON string of whatever numbers.我想要做的是用任何数字的 JSON 字符串响应。 Do I need to put a different content-type?我需要放置不同的内容类型吗? should this function pass that value to another one say on the client side?这个函数应该将该值传递给另一个在客户端说的吗?

Thanks for your help!谢谢你的帮助!

Using res.json with 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);
}
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"}

You have to use the JSON.stringify() function included with the V8 engine that node uses.您必须使用 node 使用的 V8 引擎中包含的JSON.stringify()函数。

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

Edit: As far as I know, IANA has officially registered a MIME type for JSON as application/json in RFC4627 .编辑:据我所知, IANA已在RFC4627 中将JSON 的 MIME 类型正式注册为application/json It is also is listed in the Internet Media Type list here .它也列在此处Internet 媒体类型列表中。

Per JamieL 's answer to another post :根据JamieL另一篇文章回答

Since Express.js 3x the response object has a json() method which sets all the headers correctly for you.从 Express.js 3x 开始,响应对象有一个 json() 方法,可以为您正确设置所有标头。

Example:例子:

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

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

I have used the above code in my existing project.我在现有项目中使用了上述代码。

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

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