【问题标题】:How to loop through JSON array in nodejs?如何在nodejs中循环遍历JSON数组?
【发布时间】:2016-12-09 00:52:02
【问题描述】:

我正在尝试从 json 数组中读取值以显示在页面中。我已经尝试使用下面的代码,但无法做到。我尝试了很长时间才完成这项工作,请告知我在这里做错了什么。

我也无法执行 JSON.parse- 意外输入错误。

http.request(options, function(res) {
res.on('data', function (result) {
console.log(result);//Displaying below format of result without any error
console.log(result.Reference[0].name); Error //TypeError: Cannot read property '0' of undefined.
console.log(result.Reference.length);//Error TypeError: Cannot read property 'length' of undefined

JSON 格式:打印结果时

{
        "Reference": [
            {
                "name": "xxxxxxxx",
                "typeReference": {
                 "articulation": 0,
                "locked": false,
                "createdBy": {
                     "userName": "System",
                              },
                "lastModifiedBy": {
                                  "userName": "System",
                                 },

                "lastModified": 1391084398660,
                "createdOn": 1391084398647,
                "isSystem": true
            },
            "communityReference": {
                "name": "xxxxxx",
                "language": "English",
                "sbvr": false,
                 "parentReference": {
                    "name": "xxxxx",
                    "sbvr": false,
                    "meta": false,
                    "parentReference": null,
                    "locked": false,
                    "createdBy": {
                        "userName": "xxxxx",
                           },
                    "lastModifiedBy": {
                        "userName": "xxxxx",
                           },

                    "lastModified": 1459185726230,
                    "createdOn": 1456337723119,
                    "isSystem": false
                },
                "locked": false,
                "createdBy": {
                     "userName": "xxxxx",
                           },
                "lastModifiedBy": {
                    "userName": "xxxxxx",
                          },

                "lastModified": 1472655031590,
                "createdOn": 1472654988012,
                "isSystem": false
            },
            "locked": false,
            "createdBy": {
                  "userName": "xxxxx",

            },
            "lastModifiedBy": {

                "userName": "xxxxx",
                "firstName": "xxxxx",

            },

            "lastModified": 1473171981520,
            "createdOn": 1472655253366,
            "isSystem": false
        },
        {
        "name":"yyyyyy", same attribute type as above.
          ...
        },
        {
        ..
        },

【问题讨论】:

  • 您检查过您的result 不是字符串吗?
  • 如果您在执行JSON.parse(result) 时遇到意外的输入错误,那么它可能不是有效的 JSON。
  • 如果result是字符串,首先需要将其转换为对象var obj = JSON.parse(result); obj.Reference[0];
  • 我已经使用 typeof(result) 验证了结果是字符串。

标签: javascript json node.js node-request


【解决方案1】:

res是一个流,data事件表明它已经收到了一些数据,但它可能是也可能不是所有的数据。您不可能一次获取所有数据,因此您需要等到end 事件触发,此时您拥有整个 JSON 对象:

var json = '';
res.on('data', function ( chunk ) {
  json += chunk;
} );
res.on('end', function ( ) {
  var result = JSON.parse( json );
  console.log( result.Reference[0].name );
} );

或者您可以使用json-stream,它可以逐块读取 JSON 并正确处理,这与 JSON.parse 不同。

但是,我建议您不要使用上述任何一种解决方案,而是使用request,这大大简化了发出 HTTP 请求和处理响应的其他方面。

【讨论】:

  • 我已将方法更改为请求,现在工作正常。只需删除代码并接受答案。
  • 嗨@user2848031,很高兴我的建议对您有所帮助!我不会从我的答案中删除代码,因为我认为它是首先解释导致问题的原因的一部分,我认为这是答案的重要部分。如果您宁愿接受仅提及 request 模块的答案,您可以添加该答案并自行接受,否则如果您觉得我的答案完全解决了您的问题,我感谢您以当前状态接受它。
  • 如果没有基本验证、错误检查和直接尝试从对象中读取成员,我不支持此答案。
  • @VeereshDevireddy:这有点傻。尽管很冗长,但您的答案最终只会将控制台消息从错误更改为日志。无论哪种方式,都会打印一条消息,并且所需的代码将无法继续。
【解决方案2】:

您可以通过一些额外且安全的验证来尝试此操作:

{
  if ( result ) {
    var data = (typeof result == "string") ? JSON.parse(result) : result;
    if (data.hasOwnProperty("Reference")) {
      for(var i = 0; i < data.Reference.length; i++; ) {
        try {
            var reference = data.Reference[i];
            console.log("Name:" + reference.name);
            //Your app logic
        } catch(e) {
            //In case if any invalid references, then continue with others
            console.warn("Error processing reference - " + e);
        }
      }
    } else {
      console.warn("No References were found!");
    }
  } else {
    console.error("Invalid JSON!");
  }
}

希望对你有帮助!

【讨论】:

  • 一个人不应该在没有 cmets 的情况下拒绝投票其他答案只是为了支持他们的答案。与其他答案相比,此方法在基本验证方面的效果要好得多,并且执行起来更安全。
  • 我没有投反对票,但在那条评论之后,听起来就像我投的那样,而且你的答案使用了JSON.parse,OP 说这对他们不起作用,我决定到。
猜你喜欢
  • 2021-04-26
  • 1970-01-01
  • 1970-01-01
  • 2013-02-12
  • 1970-01-01
  • 2017-11-01
  • 2011-12-25
  • 1970-01-01
相关资源
最近更新 更多