【发布时间】:2019-04-12 22:02:18
【问题描述】:
我试图找到一种方法来输出对象 json 并将它们保存在 csv 文件中,我试图在“循环 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.');
});
});
});
预期结果:
【问题讨论】:
-
预期结果似乎与输入 JSON 没有太大关系...您的任何对象中都没有“自动完成”、“多重”、“最小”或“最大”属性.目前还不清楚其中任何一个如何构成“比较”两个对象......您似乎只是想处理每个对象并输出某些属性的值。
-
您的问题不清楚?您的示例数据和结果图像不匹配
-
我的意思是期望结果只是一个例子
-
是的,它更像是遍历每个值并输出,而不是比较你的权利
-
"expect result is just a example" 好的,但如果它是基于您期望的输入数据产生的示例,我们会更容易理解.否则我们不能完全确定规则是什么。现在它看起来很随机。
标签: javascript node.js json csv