繁体   English   中英

从CSV文件中的JSON输出对象

[英]Outputting objects from json in csv file

我正在尝试找到一种方法来输出对象json并将其保存在csv文件中,我试图在“ loop for”中使用循环“ for in”,但是问题是属性和长度对象不同

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

预期结果:

在此处输入图片说明

由于您的对象可以包含不同的属性,因此您首先需要收集所有可能的属性的列表。

为此,您可以创建一个临时数组来保存属性,然后遍历对象并在该数组中推送属性(如果属性尚不存在)。

var allProps = [];

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

之后,只需要正确地构建行即可:

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

看到此代码在这里运行

输出:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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