【问题标题】:How to convert from array of json object to String in Nodejs?如何在Nodejs中将json对象数组转换为String?
【发布时间】:2017-03-29 20:57:02
【问题描述】:

我收到来自 HTTP 帖子的响应作为 json 对象数组。但想显示为字符串。请看我的回复。。

{ total: 14,
  results:
   [ { name: [Object],
       comments: [],
       attributes: [Object],
       type: [Object],
       context: [Object],
       status: 'Accepted',
       score: 1.7646775,
       modified: 1426085315767,
       parents: [] },
     { name: [Object],
       comments: [],
       attributes: [Object],
       type: [Object],
       context: [Object],
       status: 'Accepted',
       score: 1.3945999,
       modified: 1425386916807,
       parents: [] },

下面的代码显示响应。

function(error, response, data){
    if(error) {
        console.log(error);
    } else {
          console.log(data);

}

【问题讨论】:

  • 你能用console.log(JSON.stringify(data))吗?
  • 你可以用地图做到这一点:const arrAsStr = arr.map( (r) => JSON.stringify(r) );

标签: javascript json node.js node-modules


【解决方案1】:

NodeJS 有 ES5 JSON 类,其中有 stringify() 方法

function(error, response, data){
    if(error) {
      console.log(error);
    } else {
      console.log(JSON.stringify(data));
}

JSON.stringify

【讨论】:

  • 太棒了。它的工作..如何从 json 获取特定的字段值?
  • JSON.stringify() 将获取任何 javascript 对象并将其转换为 json 字符串。因此它访问 JSON 字符串中的属性,您必须将其解析回 js 对象。你可以使用JSON.parse("json string goes here")
猜你喜欢
  • 1970-01-01
  • 2017-08-15
  • 1970-01-01
  • 2016-08-03
  • 2017-08-17
  • 2019-04-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多