Skip to content
The Chat Archive
vicuna-13b Arena Human Preference 55K

Converting array of JSON object to CSV format in JavaScript, with each JSON object…

  1. 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

  2. Assistant

    To convert an array of JSON objects to CSV format in JavaScript, you can use the csv-writer library. 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-writer library 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 the createObjectCsvWriter method 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 writeRecords method to write each row to the CSV file. Finally, we call the end method to close the CSV file.

    The output of this code will be a CSV file named output.csv with 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,54321
    

    Note that the overlapping keys are separated by a dot in the CSV file.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.