1

I have used xml2js parser to parse the xml file in node.js. It is parsing the xml successfully. But now i want to parse the json or to identify the particular data in json.

My node.js code

var fs = require('fs');
var parseString = require('xml2js').parseString; 
var xml = 'C:\\temp\\Masters.xml'; 
var fileData = fs.readFileSync(xml,'utf8'); 
parseString(fileData, function (err, result) { 
console.log(JSON.stringify(result));
var json = JSON.stringify(result); 

var jsonObj = JSON.parse(json); 
for (var key in jsonObj) { 
console.dir(key + ": " + jsonObj[key].Customer_Name); 
} 
});

In console output:

'Masters: undefined'

Json data:

'{"Masters":
  {
    "Customer":

  [
  {"Customer_Name":["Kim"],
  "Customer_Code":["c86"],
  "Date":["23-11-15"],
  "Address":["Narhe"],
  "City":["Pune"],
  "State":["Maharashtra"],
  "TIN":["3365670"],
  "PAN_Number":["AAAAA1111a"],
  "Mobile_Number":["8999000090"],
  "Email_ID":["[email protected]"],
  "Contact_Person":["Anish"],
  "Opening_Balance":["0"] },

  {"Customer_Name":["Ankit"],
  "Customer_Code":["c87"],
  "Date":["12-04-15"],
  "Address":["Narhe"],
  "City":["Pune"],
  "State":["Maharashtra"],
  "TIN":["336567"],
  "PAN_Number":["AAAAA1111p"],
  "Mobile_Number":["8900000000"],
  "Email_ID":["[email protected]"],
  "Contact_Person":["Anuj"],
  "Opening_Balance":["0"] }
  ]
 }
}'

In above data, Masters is root element(Object), Customer is another nested object and there two customers. Then how can I access the customer names or how to use the for loop to access the same?.

Thanks in advance.

1
  • ohh sorry. but how can I access the customer names or any other data in this case. Commented Dec 1, 2015 at 6:16

1 Answer 1

1

You can access the Customer array as follows -

var customerArray = Masters.Customer,
    length = customerArray.length;

for(var i = 0; i < length; i++)
{
    // You can access the customers array from here - 
    console.log(customerArray[i].Customer_Name[0]); // [0] hardcoded because as you can see all the variables are in array at 0th position 
   // similarly you can access other data 
   console.log(customerArray[i].City[0]);
}
Sign up to request clarification or add additional context in comments.

1 Comment

for (var i=0; i<jsonObj["Masters"]['Customer'].length; i++){ var name= jsonObj["Masters"]['Customer'][i]; console.log(name['Customer_Name']); }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.