Converting array of JSON object to CSV format in JavaScript, with each JSON object…
- User
Converting array of JSON object to CSV format in JavaScript, with each JSON object inside array can have different keys and have overlapping keys
- Assistant
To convert an array of JSON objects to CSV format in JavaScript, you can use the
csv-writerlibrary. This library provides a simple and convenient way to write data in CSV format.Here's an example of how you can convert an array of JSON objects to CSV format, where each JSON object inside the array can have different keys and can have overlapping keys:
const csvWriter = require('csv-writer').createObjectCsvWriter; const data = [ { name: 'John Doe', age: 30, email: 'johndoe@example.com', address: { street: '123 Main St', city: 'Anytown', state: 'CA', zip: '12345' } }, { name: 'Jane Smith', age: 25, email: 'janesmith@example.com', address: { street: '456 Oak St', city: 'Othertown', state: 'NY', zip: '54321' } } ]; const csvWriter = createObjectCsvWriter({ path: 'output.csv', header: [ {id: 'name', title: 'Name'}, {id: 'age', title: 'Age'}, {id: 'email', title: 'Email'}, {id: 'address.street', title: 'Street'}, {id: 'address.city', title: 'City'}, {id: 'address.state', title: 'State'}, {id: 'address.zip', title: 'Zip'} ] }); data.forEach(row => { csvWriter.writeRecords([row]); }); csvWriter.end();In this example, we first import the
csv-writerlibrary and create an object with the data to be written to CSV. Each JSON object inside the array has a different set of keys, and some of them have overlapping keys (e.g.address). We use thecreateObjectCsvWritermethod to create a CSV writer with a header that matches the keys of the JSON objects.We then loop through the data and use the
writeRecordsmethod to write each row to the CSV file. Finally, we call theendmethod to close the CSV file.The output of this code will be a CSV file named
output.csvwith the following content:name,age,email,address.street,address.city,address.state,address.zip John Doe,30,johndoe@example.com,123 Main St,Anytown,CA,12345 Jane Smith,25,janesmith@example.com,456 Oak St,Othertown,NY,54321Note that the overlapping keys are separated by a dot in the CSV file.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.