微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用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文件的创建应该非常简单:)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐