Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How can I convert json object with array to csv? #412

Open
DevRockstarZ opened this issue Dec 10, 2023 · 1 comment
Open

How can I convert json object with array to csv? #412

DevRockstarZ opened this issue Dec 10, 2023 · 1 comment

Comments

@DevRockstarZ
Copy link

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!

@hadyrashwan
Copy link

hadyrashwan commented Jan 11, 2024

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants