如何使用node.js访问json对象的子元素

在我的node.js应用程序中,我从 mongodb服务器检索值,并希望将它们转换为CSV文件.可以从数据库轻松访问父元素并显示在CSV文件中但子元素不显示且无法访问..

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 + '","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');
      });
   });
 }  
});

除时间段的子元素外,显示所有值.
如何从数据库访问JSON的子元素并显示CSV文件中的所有值?

解决方法

可以在 following thread(访问嵌套数据结构)的答案中找到访问嵌套元素的简单方法.

A nested data structure is an array or object which refers to other arrays or objects,i.e. its values are arrays or objects. Such structures can be accessed by consecutively applying dot or bracket notation.

As we can see timeSlot is an object,hence we can access its properties using dot notation. The items property is accessed as follows:

timeSlot.id

Alternatively,we Could have used bracket notation for any of the properties,especially if the name contained characters that would have made it invalid for dot notation usage:

var item_name = timeSlot['id'];

获得所需的所有数据后,CSV文件的创建应该非常简单:)

相关文章

这篇文章主要介绍“基于nodejs的ssh2怎么实现自动化部署”的...
本文小编为大家详细介绍“nodejs怎么实现目录不存在自动创建...
这篇“如何把nodejs数据传到前端”文章的知识点大部分人都不...
本文小编为大家详细介绍“nodejs如何实现定时删除文件”,内...
这篇文章主要讲解了“nodejs安装模块卡住不动怎么解决”,文...
今天小编给大家分享一下如何检测nodejs有没有安装成功的相关...