2014-12-08 31 views
8

在我的node.js應用程序中,我從mongodb服務器中檢索值,並希望將它們轉換爲CSV文件。父元素很容易從數據庫訪問並顯示在CSV文件,但該子元素不被顯示,並且不能被訪問..如何使用node.js訪問json對象的子元素

JSON結構:

"name" : "fhj", 
"age" : "23", 
"gender" : "female", 
"sec" : "b", 
"username" : "9886666", 
"language" : "HINDI", 
"method" : "method2", 
"timeSlot" : { 
    "id" : 2, 
    "fromTime" : 12, 
    "toTime" : 15 
} 

mycode的:顯示除了蘇

db.users.find(function(err,values){ 
if(err||!values.length) 
    console.log("ERROR !!!!"); 
else 
{ 
    var i=1; 
    str='['; 
    values.forEach(function(user){ 
    if(i==values.length) 
     str=str+'{ "name" : "' + user.username + '","age" : "'+ user.age +'","gender":"'+user.gender+'","sec":"'+user.sec+'","username":"'+user.username+'","language":"'+user.language+'","method":"'+user.method+'","Timeslot":"'+user.timeslot+'"}'; 
    else{ 
     str = str + '{ "name" : "' + user.username + '","age" : "'+ user.age +'","gender":"'+user.gender+'","sec":"'+user.sec+'","username":"'+user.username+'","language":"'+user.language+'","method":"'+user.method+'","Timeslot":"'+user.timeslot+'"},' +'\n'; 
     i++; 
    } 
    }); 
    str = str.trim(); 
    str = str + ']'; 
    var obj=JSON.parse(str); 
    json2csv({data: obj, fields: ['name', 'age','gender','sec','username','language','method','Timeslot']}, function(err, csv) { 
     if (err) 
      console.log(err); 
     fs.writeFile('./files/user.csv', csv, function(err) { 
     if (err) 
      throw err; 
     console.log('File saved'); 
     }); 
    }); 
} 
}); 

的所有值b時隙的元素。 如何從數據庫訪問JSON的子元素並顯示CSV文件中的所有值?

+0

你能否提供創建user.csv文件。我遇到了與json2csv模塊類似的問題。對於內嵌的對象/數組,它不支持複雜的結構。 – 2016-08-04 12:49:11

+0

@SaleemAhmed你必須手動創建嵌套json的csv。 – Subham 2016-08-04 12:51:14

回答

0

嘗試使用user.timeslot.fromTime & &做一個鍵/值對每個子元素

+0

它顯示錯誤:無法讀取未定義的屬性'fromTime' – Subham 2014-12-08 11:22:35

0

嘗試這樣的。這會將來自timeSlot對象的所有數據合併到單個字符串中。您可以根據需要對該字符串進行格式化。代碼添加forEach循環。

var strToAdd = ""; 
for (var k in timeSlot) { 
strToAdd += k + timeSlot[k] + "->"; 
} 

...+"Timeslot":"'+strToAdd+'".... 

希望這會有所幫助。

0

看來問題是,在你的forEach循環你在哪裏迭代變量values您正在訪問的財產user,而不是價值的usertimeSlottimeslot。記住大小寫敏感問題!

Here is a fiddle which demonstrates that changing the case of the object property in lines 24 and 25 solves the issue

在鏈接的例子我也該字符串化的對象,這樣我可以把它寫入文件,看看輸出清晰。我會建議您不要這樣做,因爲您可能會遇到後續解析問題。相反,你應該通過訪問該對象的屬性來構造一個字符串。

無論如何,你有一個錯誤的原因是你的原始代碼中的大小寫敏感問題。我希望這有幫助。

1

嘗試像下面

db.users.find(function(err, users){ 
     if (err || !users.length) 
      return console.log(err || 'Users not found'); 

     // List of column to export to cvs 
     var columns = ['name', 'age', 'gender', 'sec', 'username', 'language', 'method', 'timeSlot']; 

     var text = users.reduce(function(text, user){ 
      // user is object e.g. {name : "fhj", age : "23", .. } 
      // If user is json then `user = JSON.parse(user, columns);` 

      // convert user to csv-line 
      text += columns.reduce(function(line, col){ 
       // I'm don't know how timeSlot must be save => save as json 
       line += (type user[col] == 'object') ? JSON.stringify(user[col], ['id', 'fromTime', 'toTime']) : user[col]; 
       line += ';'; 
       return line; 
      }, '') + '\n'; 

      return text; 
     }, ''); 

     fs.writeFile('./files/user.csv', text, function(err) { 
      if (err) 
       throw err; 

      console.log('File saved'); 
     }); 
    }); 
2

訪問嵌套元素的一個簡單的方法可以在following thread訪問嵌套數據結構)的答案被發現。

嵌套數據結構是引用其他數組或對象的數組或對象,即它的值是數組或對象。可以通過連續應用點或括號表示來訪問這些結構。

正如我們所看到的,timeSlot是一個對象,因此我們可以使用點符號來訪問它的屬性。該項目屬性進行訪問如下:

timeSlot.id 

或者,我們也可以使用括號標記的任何屬性,尤其是名稱載有將使它無效的點符號使用的字符:

var item_name = timeSlot['id']; 

一旦你擁有你所需要的數據時,CSV文件的創建應該是相當簡單的:)

0

當您讀取結構化數據(這裏是:JSON)並且想要將其轉換爲展平數據(這裏是:csv)時,您必須決定如何執行展平。

換句話說 - 你的目標CSV文件的結構可能是以下幾點:

name, age, gender, sec, username, language, method, timeSlot_id, timeSlot_fromTime, timeSlot_toTime 
"fhb","23","female","b","9886666","HINDI","method2",2,12,15 

一旦你決定要壓平時隙這種方式給出的結構,可以使用從@Aikon的言論Mokwai只是沒有字符串化 - 使用數組表示法如通過@trolologuy描述讀取結構:

var timeSlot_id = timeSlot['id]'; 
var timeSlot_fromTime = timeSlot['fromTime']; 
var timeSlot_toTime = timeSlot['toTime']; 

隨後,誰讀取CSV要明白,你扁平的數據但不會不必解析任何結構,因爲您確實提供了平坦的數據記錄(因爲csv最喜歡它)。

希望它有幫助!

0

嗨使用異步foreach循環來實現上述。這裏詳細說明它是如何工作的。

Async loop in nodejs

0
var json= { 
"name" : "fhj", 
"age" : "23", 
"gender" : "female", 
"sec" : "b", 
"username" : "9886666", 
"language" : "HINDI", 
"method" : "method2", 
"timeSlot" : { 
    "id" : 2, 
    "fromTime" : 12, 
    "toTime" : 15 
} 
}; 
console.log(json.timeSlot['id']); 
console.log(json.timeSlot['fromTime']); 
console.log(json.timeSlot['toTime']); 

享受:)

看到jsfiddle