如何在node.js中访问json嵌套对象

时间:2015-12-01 06:06:17

标签: json xml node.js

我使用xml2js解析器来解析node.js中的xml文件。它正在成功解析xml。但现在我想解析json或识别json中的特定数据。

我的node.js代码

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); 
} 
});

在控制台输出中:

'Masters: undefined'

Json数据:

'{"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":["amitshirke@gmail.com"],
  "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":["amitshirke1@gmail.com"],
  "Contact_Person":["Anuj"],
  "Opening_Balance":["0"] }
  ]
 }
}'

在上面的数据中,Masters是根元素(Object),Customer是另一个嵌套对象,还有两个客户。那么如何访问客户名称或如何使用for循环来访问客户名称?。

提前致谢。

1 个答案:

答案 0 :(得分:1)

您可以按如下方式访问Customer数组 -

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]);
}