Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access child element of json object using node.js

Tags:

json

node.js

csv

In my node.js app I retrieve values from mongodb server and want to convert them to a CSV file.The parent element is easily accessed from the database and displayed in the CSV file but the sub element is not displayed and can't be accessed..

JSON structure:

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

All the values are displayed except the sub element of timeslot. How can I access the sub element of the JSON from the database and display all the values in a CSV file???

like image 250
Subham Avatar asked Dec 08 '14 09:12

Subham


2 Answers

An easy way of accessing the nested elements can be found on the answer of following thread (Accessing nested data structures).

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'];

Once you have all the data you need, the creation of the CSV-file should be quite straightforward :)

like image 195
trolologuy Avatar answered Sep 23 '22 14:09

trolologuy


Try like below

    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');
        });
    });
like image 22
Aikon Mogwai Avatar answered Sep 23 '22 14:09

Aikon Mogwai