Thursday, 11 May 2017

Excel to JSON node parser: I'm having trouble saving JSON output to a file

I follow one of the solutions from here. The solution logs out to the console well, but I don't know how to save it properly to a .json file. I've tried using File System module to record the output to a .json file but all I get is a bunch of Object.

var fs = require('fs');
var XLSX = require('xlsx');
var workbook = XLSX.readFile('test.xlsx');
var sheet_name_list = workbook.SheetNames;
sheet_name_list.forEach(function(y) {
    var worksheet = workbook.Sheets[y];
    var headers = {};
    var data = [];
    for(z in worksheet) {
        if(z[0] === '!') continue;
        //parse out the column, row, and value
        var col = z.substring(0,1);
        var row = parseInt(z.substring(1));
        var value = worksheet[z].v;

        //store header names
        if(row == 1) {
            headers[col] = value;
            continue;
        }

        if(!data[row]) data[row]={};
        data[row][headers[col]] = value;
    }
    //drop those first two rows which are empty
    data.shift();
    data.shift();
    //console.log(data);
    fs.writeFileSync("new.json", data, function(err) {
        if(err) {
            return console.log(err);
        }
    }); 
});

output of new.json

[object Object],[object Object],[object Object],[object Object], ...



via myhouse

No comments:

Post a Comment