node-csv icon indicating copy to clipboard operation
node-csv copied to clipboard

How can I convert json object with array to csv?

Open DevRockstarZ opened this issue 2 years ago • 1 comments

Describe the bug

I've installed csv-stringify via npm install.

To Reproduce

import { stringify as csvStringify } from "csv-stringify/sync";
jsonString = `{"test":["1","2"]}`
jsonData = JSON.parse(jsonString);
console.log(csvStringify([jsonData], { delimiter: ",", header: true }));

Additional context

I've expecting result as below.

test
1
2

But the result came as below.

test
"[""1"",""2""]"

Thanks for your help!

DevRockstarZ avatar Dec 10 '23 09:12 DevRockstarZ

Hey @DevRockstarZ,

This is how it's done:

import { stringify as csvStringify } from "csv-stringify/sync";
const jsonString = `{"test":["1","2"],"test2":["1","2"],"test3":["1"]}`
const jsonData = JSON.parse(jsonString);
const headers = Object.keys(jsonData)
let csvLength = 0
const csvData = []
console.log('headers',headers)
for( const head of headers){
    csvLength = jsonData[head].length > csvLength ? jsonData[head].length : csvLength
}
console.log('csvLength',csvLength)
for (let i = 0; i < csvLength; i++) {
    console.log("Iteration:", i);
    const row =  headers.reduce((accumulator, currentValue) => ({[currentValue]:jsonData[currentValue][i] ?? '',...accumulator}),{})
    csvData.push(row)
    console.log('row',row)
    console.log('csvData',row)
}

console.log('final','csvData',csvData)
console.log('output')
console.log(csvStringify(csvData, {  header: true }));

You can find more info in the docs

hadyrashwan avatar Jan 11 '24 08:01 hadyrashwan