使用Node.js中的JSON对象进行响应(将对象/数组转换为JSON字符串) [英] Responding with a JSON object in Node.js (converting object/array to JSON string)

查看:508
本文介绍了使用Node.js中的JSON对象进行响应(将对象/数组转换为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();
}

这基本上只打印字符串应该以形式出现的随机数字JSON。我想要做的是使用任何数字的JSON字符串进行响应。我需要使用不同的内容类型吗?该函数应该将该值传递给客户端的另一个吗?

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?

感谢您的帮助!

推荐答案

使用Express的 res.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"
  });
}

另外:

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

这篇关于使用Node.js中的JSON对象进行响应(将对象/数组转换为JSON字符串)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆