最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Unable to loop through a JSON object in NodeJS - Stack Overflow

programmeradmin1浏览0评论

I have a NODEJS program that uses xml2js to convert XML file to JSON and parse it. I am then trying to loop through the json object and display the ID, LastReportTime for each of them but the output i get says undefined

Output

2015-02-26T18:45:35.34-0500 [App/0]   OUT BESAPI
2015-02-26T18:45:35.34-0500 [App/0]   OUT Computer
2015-02-26T18:45:35.34-0500 [App/0]   OUT Computer:undefined
2015-02-26T18:45:35.34-0500 [App/0]   OUT Done

NodeJS

var fs = require('fs'),
    xml2js = require('xml2js');

var parser = new xml2js.Parser();
fs.readFile('myfile.xml', function(err, data) {
    parser.parseString(data, function (err, result) {

        var jsoniem = JSON.stringify(result);
        console.log(jsoniem);
        var data = JSON.parse(jsoniem);

        for (var obj in data) {
          if (data.hasOwnProperty(obj)) {
            console.log(obj);
            console.log("\n \n");

            if (obj == "BESAPI") {

              for (var prop in data[obj]) {
                console.log(prop);
                if (prop == "Computer") {
                   console.log(prop + ':' + data[obj][prop].ID);
                   console.log(prop + ':' + data[obj][prop].LastReportTime);
                }

              }

            } 

          }

        }

        console.log('Done');
    });

Json (After the program converts from XML to JSON)

{
    "BESAPI": {
        "$": {
            "xmlns:xsi": "",
            "xsi:noNamespaceSchemaLocation": "BESAPI.xsd"
        },
        "Computer": [
            {
                "$": {
                    "Resource": "api/puter/2431038"
                },
                "LastReportTime": [
                    "Thu, 26 Feb 2015 14:54:41 +0000"
                ],
                "ID": [
                    "2431038"
                ]
            },
            {
                "$": {
                    "Resource": "api/puter/16710075"
                },
                "LastReportTime": [
                    "Thu, 26 Feb 2015 14:45:18 +0000"
                ],
                "ID": [
                    "16710075"
                ]
            },
            {
                "$": {
                    "Resource": "api/puter/3415985"
                },
                "LastReportTime": [
                    "Thu, 26 Feb 2015 14:50:52 +0000"
                ],
                "ID": [
                    "3415985"
                ]
            }
        ]
    }
}

XML

<?xml version="1.0" encoding="UTF-8"?>
<BESAPI xmlns:xsi="" xsi:noNamespaceSchemaLocation="BESAPI.xsd">
    <Computer Resource="api/puter/2431038">
        <LastReportTime>Thu, 26 Feb 2015 14:54:41 +0000</LastReportTime>
        <ID>2431038</ID>
    </Computer>
    <Computer Resource="api/puter/16710075">
        <LastReportTime>Thu, 26 Feb 2015 14:45:18 +0000</LastReportTime>
        <ID>16710075</ID>
    </Computer>
    <Computer Resource="api/puter/3415985">
        <LastReportTime>Thu, 26 Feb 2015 14:50:52 +0000</LastReportTime>
        <ID>3415985</ID>
    </Computer>
</BESAPI>

I have a NODEJS program that uses xml2js to convert XML file to JSON and parse it. I am then trying to loop through the json object and display the ID, LastReportTime for each of them but the output i get says undefined

Output

2015-02-26T18:45:35.34-0500 [App/0]   OUT BESAPI
2015-02-26T18:45:35.34-0500 [App/0]   OUT Computer
2015-02-26T18:45:35.34-0500 [App/0]   OUT Computer:undefined
2015-02-26T18:45:35.34-0500 [App/0]   OUT Done

NodeJS

var fs = require('fs'),
    xml2js = require('xml2js');

var parser = new xml2js.Parser();
fs.readFile('myfile.xml', function(err, data) {
    parser.parseString(data, function (err, result) {

        var jsoniem = JSON.stringify(result);
        console.log(jsoniem);
        var data = JSON.parse(jsoniem);

        for (var obj in data) {
          if (data.hasOwnProperty(obj)) {
            console.log(obj);
            console.log("\n \n");

            if (obj == "BESAPI") {

              for (var prop in data[obj]) {
                console.log(prop);
                if (prop == "Computer") {
                   console.log(prop + ':' + data[obj][prop].ID);
                   console.log(prop + ':' + data[obj][prop].LastReportTime);
                }

              }

            } 

          }

        }

        console.log('Done');
    });

Json (After the program converts from XML to JSON)

{
    "BESAPI": {
        "$": {
            "xmlns:xsi": "http://www.w3/2001/XMLSchema-instance",
            "xsi:noNamespaceSchemaLocation": "BESAPI.xsd"
        },
        "Computer": [
            {
                "$": {
                    "Resource": "api/puter/2431038"
                },
                "LastReportTime": [
                    "Thu, 26 Feb 2015 14:54:41 +0000"
                ],
                "ID": [
                    "2431038"
                ]
            },
            {
                "$": {
                    "Resource": "api/puter/16710075"
                },
                "LastReportTime": [
                    "Thu, 26 Feb 2015 14:45:18 +0000"
                ],
                "ID": [
                    "16710075"
                ]
            },
            {
                "$": {
                    "Resource": "api/puter/3415985"
                },
                "LastReportTime": [
                    "Thu, 26 Feb 2015 14:50:52 +0000"
                ],
                "ID": [
                    "3415985"
                ]
            }
        ]
    }
}

XML

<?xml version="1.0" encoding="UTF-8"?>
<BESAPI xmlns:xsi="http://www.w3/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="BESAPI.xsd">
    <Computer Resource="api/puter/2431038">
        <LastReportTime>Thu, 26 Feb 2015 14:54:41 +0000</LastReportTime>
        <ID>2431038</ID>
    </Computer>
    <Computer Resource="api/puter/16710075">
        <LastReportTime>Thu, 26 Feb 2015 14:45:18 +0000</LastReportTime>
        <ID>16710075</ID>
    </Computer>
    <Computer Resource="api/puter/3415985">
        <LastReportTime>Thu, 26 Feb 2015 14:50:52 +0000</LastReportTime>
        <ID>3415985</ID>
    </Computer>
</BESAPI>
Share Improve this question edited Feb 27, 2015 at 0:03 user3846091 asked Feb 26, 2015 at 23:52 user3846091user3846091 1,7037 gold badges25 silver badges31 bronze badges 1
  • Is your question answered ? Y bounty still ? – Nielarshi Commented Mar 7, 2015 at 18:01
Add a ment  | 

5 Answers 5

Reset to default 5 +50

Considering your JSON example iterating over object seems irrelevant. Also there is no need to stringify data first and then parse the string.

fs.readFile('myfile.xml', function(err, data) {
  parser.parseString(data, function (err, result) {

    var jsoniem = JSON.stringify(result);
    console.log(jsoniem);

    result.BESAPI.Computer.forEach(function (el) {
      // Output arrays
      console.log(el.ID);
      console.log(el.LastReportTime);

      // Get first elements
      console.log(el.ID[0]);
      console.log(el.LastReportTime[0]);
    });

  }

  console.log('Done');
});

Problem why you were getting undefined was that

object data[obj][prop] was an array not an object

So, again getting each object in that array you had missed, Just modified your innermost "if" block.

var fs = require('fs'),
    xml2js = require('xml2js');

var parser = new xml2js.Parser();
fs.readFile('myfile.xml', function(err, data) {
    parser.parseString(data, function (err, result) {

        var jsoniem = JSON.stringify(result);
        console.log(jsoniem);
        var data = JSON.parse(jsoniem);

        for (var obj in data) {
          if (data.hasOwnProperty(obj)) {
            console.log(obj);
            console.log("\n \n");

            if (obj == "BESAPI") {

              for (var prop in data[obj]) {
                console.log(prop);


                if (prop == "Computer") {

                   for (var propKeys in prop) {
                      if(data[obj] && data[obj][prop] && data[obj][prop][0]) {
                         console.log(prop, data[obj][prop][0].ID);
                         console.log(prop, data[obj][prop][0].LastReportTime);
                      } 
                   }
                }

              }

            } 

          }

        }

        console.log('Done');
    });
});

It seems you are not iterating the puter array. Try changing the inner loop something like this:

for (var prop in data[obj]) {
            console.log(prop);
            if (prop == "Computer") {
               for( var cmp in data[obj][prop] ) {
               console.log(prop + ':' + cmp.ID[0]);
               console.log(prop + ':' + cmp.LastReportTime[0]);
             }
            }

          }

Update Added the array notation to the ID and LastReportTime as well per your JSON

You're missing one more loop, as Computer property is an array of arrays:

       if (obj == "BESAPI") {

          for (var prop in data[obj]) {
            console.log(prop);
            if (prop == "Computer") {
               // loop over Computer dataseries
               for(var id in data[obj][prop]) {
                   console.log(prop + ':' + data[obj][prop][id].ID);
                   console.log(prop + ':' + data[obj][prop][id].LastReportTime);
               }
            }

          }

When reading JSON element we need to take care of Index and array In your case

for(var i=0; i <data.BESAPI.Computer.length; i++ ){
    var puterData = data.BESAPI.Computer[i];

    alert(puterData.LastReportTime);
}

Solved the problem. you can even see working FIDDLE

发布评论

评论列表(0)

  1. 暂无评论