简体   繁体   中英

Outputting objects from json in csv file

I'm trying to find a way to output objects json and save them in csv file, i was trying to use loop 'for in' in 'loop for ' but the problem is that property and length object are different

data json:

[ 
{"name":"Googlebot","htmlimports":true,"objectfit":true,"geolocation":true,"histor":true,"es5object":true,"strictmode":true,"es5string":true}, 

{"name":"Bing","htmlimports":false,"geolocation":true,"history":true,"es5object":true,"strictmode":true,"es5string":true}, 

{"name":"iE","htmlimports":true,"svgclippaths":true,"geolocation":true,"history":true,"ie8compat":false,"strictmode":true,"es5string":true,"es5syntax":true} ]


const stringify = require('csv-stringify');
const fs = require('fs')

fs.readFile('./googleBot.json','utf8', (err, dataa) => {
  if (err) throw err;
  const dates  = JSON.parse(dataa)

  let data = [];
  let columns = {
    value: 'value',
    Googlebot: 'Googlebot',
    Bing: 'Bing',
    iE: 'iE',
  };

  for(i = 0; i < dates.length; i++){
    for (var prop in dates) {
      data.push([prop, `${dates[0][prop]}`, `${dates[1][prop]}`, `${dates[2][prop]}`]);
    }
  }


  stringify(data, { header: true, columns: columns }, (err, output) => {
    if (err) throw err;
    fs.writeFile('my.csv', output, (err) => {
      if (err) throw err;
      console.log('my.csv saved.');
    });
  });
});

expected result:

在此处输入图片说明

Because your objects can contain different properties, you first need to gather a list of all possible properties.

You can do this by creating a temporary array to hold properties, and iterating over your objects and pushing properties in this array, if they're not already there.

var allProps = [];

for (var i = 0; i < dates.length; i++) {
  for (var prop in dates[i]) {
    if (!allProps.includes(prop)) {
      allProps.push(prop);
    }
  }
}

After that, it's just a matter of constructing your rows properly:

for (var i = 0; i < allProps.length; i++) {
  var prop = allProps[i];
  if (prop == 'name') continue;  //skip the name property, it's alrady in the columns

  var row = []
  row.push(prop);  //first entry in the row is the property name

  for (var k = 0; k < dates.length; k++) {
    row.push(`${dates[k][prop]}`);
  }

  data.push(row);
}

See this code running here

Output:

value,Googlebot,Bing,iE
htmlimports,true,false,true
objectfit,true,undefined,undefined
geolocation,true,true,true
histor,true,undefined,undefined
es5object,true,true,undefined
strictmode,true,true,true
es5string,true,true,true
history,undefined,true,true
svgclippaths,undefined,undefined,true
ie8compat,undefined,undefined,false
es5syntax,undefined,undefined,true

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM