2017-04-17 83 views
0

我使用BabyParse將本地CSV文件轉換爲JSON。這裏是js文件我已經寫了做它:將生成的JSON寫入文件,BabyParse

var Baby = require('babyparse'); 
var fs = require('fs'); 
var file = 'test2.csv'; 
var content = fs.readFileSync(file, { encoding: 'binary' }); 

parsed = Baby.parse(content, {fastMode: false}); 
rows = parsed.data; 
console.log(rows); 

fs.writeFile("blahblahblah.json", rows, function(err) { 
    if(err) { 
     return console.log(err); 
    } 

    console.log("The file was saved!"); 
}); 

的JSON由console.log(rows)線輸出到控制檯似乎是正確的(ISH)。但是,當我將rows寫入文件時,所有JSON樣板消失。例如,這裏是我在嘗試時,下面的csv文件轉換:

col1,col2,col3 
"val1","val2","val3" 
"val1","val2","val3" 
"val1","val2","val3" 

這就是被打印到控制檯:

[ [ 'col1', 'col2', 'col3' ], 
    [ 'val1', 'val2', 'val3' ], 
    [ 'val1', 'val2', 'val3' ], 
    [ 'val1', 'val2', 'val3' ], 
    [ '' ] ] 

,但是這是被寫入文件:

col1,col2,col3,val1,val2,val3,val1,val2,val3,val1,val2,val3, 

有沒有人知道這裏發生了什麼?爲什麼JSON特定的語法被剝離?

回答

1

您需要將json轉換爲字符串,然後再保存它。

rows = JSON.stringify(parsed.data); 
1

這應該是訣竅!

fs.writeFile("blahblahblah.json", JSON.stringify(Baby.parse(content, {fastMode: false}).data), function(err) { 
     if(err) { 
      return console.log(err); 
     } 

     console.log("The file was saved!"); 
    });