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

发布于 2024-11-05 07:51:46 字数 436 浏览 0 评论 0原文

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

感谢您的帮助!

I'm a newb to back-end code and I'm trying to create a function that will respond to me a JSON string. 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". What I want this to do is respond with a JSON string of whatever numbers. 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!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

残疾 2024-11-12 07:51:46

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

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

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);
}
浪荡不羁 2024-11-12 07:51:46
var objToJson = { };
objToJson.response = response;
response.write(JSON.stringify(objToJson));

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

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

If you alert(JSON.stringify(objToJson)) you will get {"response":"value"}

软的没边 2024-11-12 07:51:46

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

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

编辑:据我所知,IANA已在 RFC4627application/json一个>。它也列在互联网媒体类型列表此处

You have to use the JSON.stringify() function included with the V8 engine that node uses.

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. It is also is listed in the Internet Media Type list here.

烟若柳尘 2024-11-12 07:51:46

根据JamieL答案< /a> 到另一篇文章

自 Express.js 3x 起,响应对象有一个 json() 方法,该方法设置
所有标题都适合您。

示例:

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

Per JamieL's answer to another post:

Since Express.js 3x the response object has a json() method which sets
all the headers correctly for you.

Example:

res.json({"foo": "bar"});
£冰雨忧蓝° 2024-11-12 07:51:46

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

in express there may be application-scoped JSON formatters.

after looking at express\lib\response.js, I'm using this routine:

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);
}
坏尐絯℡ 2024-11-12 07:51:46
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);

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

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.

十级心震 2024-11-12 07:51:46

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

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

了解更多

The JSON.stringify() method converts a JavaScript object or value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.

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

know more

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文