簡體   English   中英

如何在node.js中訪問json嵌套對象

[英]How to access json nested objects in 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是根element(Object),Customer是另一個嵌套對象,並且有兩個客戶。 那么,如何訪問客戶名稱或如何使用for循環訪問客戶名稱呢?

提前致謝。

您可以按以下方式訪問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]);
}

暫無
暫無

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

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