簡體   English   中英

如何在Node.js中循環遍歷JSON數組?

[英]How to loop through JSON array in nodejs?

我正在嘗試從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.
          ...
        },
        {
        ..
        },

res是一個流,並且data事件表明它已接收到一些數據,但是它可能是也可能不是全部數據。 當您擁有整個JSON對象時,您不太可能一次獲取所有數據,因此需要等待end事件觸發:

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請求和處理響應的過程以及其他方面。

您可以通過一些其他安全的驗證來嘗試此操作:

{
  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!");
  }
}

希望能幫助到你!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM