Transform Json data into CSV file format with customized headers and formatting

I have a function in my code that fetches JSON data from an endpoint and converts it into a CSV file. Is there a way for me to specify specific headers and the order of columns I want in this CSV file?

function downloadJSONAsCSV(endpoint) {
    // Fetch JSON data from the endpoint
    fetch(endpoint)
        .then(response => response.json())
        .then(jsonData => {
            // Convert JSON data to CSV
            let csvData = jsonToCsv(jsonData.items.data); // Add .items.data
            // Create a CSV file and allow the user to download it
            let blob = new Blob([csvData], { type: 'text/csv' });
            let url = window.URL.createObjectURL(blob);
            let a = document.createElement('a');
            a.href = url;
            a.download = 'data.csv';
            document.body.appendChild(a);
            a.click();
        })
        .catch(error => console.error(error));
}

function jsonToCsv(jsonData) {
    let csv = '';
    // Get the headers
    let headers = Object.keys(jsonData[0]);
    csv += headers.join(',') + '\n';
    // Add the data
    jsonData.forEach(function (row) {
        let data = headers.map(header => JSON.stringify(row[header])).join(','); // Add JSON.stringify statement
        csv += data + '\n';
    });
    return csv;
}

Desired CSV format:

"Batch Code","Order Id","Batch Status","Batch Expiration Date","Total","Used","Remaining","Redemption Method","Type","Organization Group","Employee ID","Selection Type"
"B-E7BE5602-2F9B-E3","11608501","Active","2023-06-29","1","0","1","ID CARD","OPEN","Yes","Yes","FLOWER"
"B-480A8929-57D5-97","11608502","Active","2023-06-29","1","0","1","ID CARD","OPEN","No","No","FLOWER"

JSON input that needs to be converted into CSV:

{
    "numOfItems": {
        "records": 2,
        "data": [{
                "numOfIDs": 1,
                "productId": null,
                "askOrgId": "Yes",
                "orderId": 11608501,
                "orgSelectionType": "FLOWER",
                "batchCode": "B-E7BE5602-2F9B-E3",
                "Type": "OPEN",
                "batchId": 413,
                "creationDate": "2022-06-29",
                "isOnline": "Yes",
                "productName": null,
                "batchProductArray": [{
                        "ID": 663255,
                        "TYPE": "PRODUCT",
                        "NAME": "SomeName"
                    }
                ],
                "numOfUsedPassports": 0,
                "redemptionMethod": "ID Card",
                "askSSN": "No",
                "askEmployeeId": "Yes",
                "batchStatus": "Active",
                "productType": null,
                "expirationDate": "2023-06-29"
            }
        ],
        "draw": 1,
        "recordsTotal": 2
    }
}

I attempted to map this JSON data into a specific format but was unsuccessful with that.

Answer №1

To optimize the coding process, it is recommended to create two arrays: one for defining property names and order, and another for actual column names. The code can then be structured like this:

const data = [{
    "numOfIDs": 1,
    "productId": null,
    "askOrgId": "Yes",
    "orderId": 11608501,
    "orgSelectionType": "FLOWER",
    "batchCode": "B-E7BE5602-2F9B-E3",
    "Type": "OPEN",
    "batchId": 413,
    "creationDate": "2022-06-29",
    "isOnline": "Yes",
    "productName": null,
    "batchProductArray": [{
        "ID": 663255,
        "TYPE": "PRODUCT",
        "NAME": "SomeName"
    }
    ],
    "numOfUsedPassports": 0,
    "redemptionMethod": "ID Card",
    "askSSN": "No",
    "askEmployeeId": "Yes",
    "batchStatus": "Active",
    "productType": null,
    "expirationDate": "2023-06-29"
}
];

const header = ["Batch Code","Order Id"];
const headerProps = ["batchCode", "orderId"]
let csv = header.map(s => "\"" + s + "\"").join(",") + "\n";

data.forEach( r => {
    headerProps.forEach((c,i) => csv += (i>0 ? ", " : "")+ "\"" +r[c]+ "\"")
    csv += "\n";
})

console.log(csv);

UPDATE: Alternatively, a simpler version inspired by derpirscher:

data.forEach( r => csv += headerProps.map(h => `"${r[h]}"`).join(",") + "\n")

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Changing a JSON file using Qt

I am looking to manipulate an existing JSON file by making changes such as replacing, deleting, and adding objects, arrays, and key-value pairs before saving the modifications back to the file. Currently, I have been attempting to edit a JSON file that l ...

NodeJS Exporting Features

A situation is in front of me: var express = require('express'); var router = express.Router(); var articles = require('../model/articles.js'); router.get('/all', function(req, res, next) { res.json(articles.getAll()); ...

Serialization of Passport Session failed due to a Bad Gateway error

I am currently utilizing the following dependencies: express session passport passport-local passport-local-mongoose Upon registering a user and posting the data, the information is successfully saved to the database, but a bad request error is generated ...

The Mustache feature is bringing back old information alongside fresh updates

Currently, I am utilizing mustache.js to display JSON data in a template. However, I have encountered an issue where Mustache is appending previous response data along with the new one when I make a $.ajax post request. How can I prevent Mustache from reta ...

Exploring the world of web programming

Looking for top-notch resources to learn about JavaScript, AJAX, CodeIgniter and Smarty. Any recommendations? ...

Is it possible to modify a specific index within an array stored in Firestore?

How can I modify a specific index within an array stored in Firebase/firestore? export const editComment = (comment) => { return (dispatch, getState, { getFirebase, getFirestore }) => { const firestore = getFirestore(); firestore.collec ...

How to toggle the visibility of specific div elements within a v-for loop depending on their content?

I am working on a scenario where I have a collection of objects displayed in a v-for loop. Each object has a specific key value pair, and I want the user to be able to toggle a button outside the loop to show or hide elements based on that key value. Initi ...

Parse JSON files from a folder and concatenate them to a CSV using Node.js

Thank you for offering your help. I have a collection of JSON files located in a directory with unknown names. I need help with the following: (1) Reading all the JSON files (2) Appending the data from the JSON files to output.csv (3) Adding "-Appended" t ...

React-router Link failing to load content

In my current development setup, I am utilizing React and Rails with AWS S3 to create a platform similar to YouTube. I've encountered an issue with navigating to different video content within a watch page using react-router. When clicking on a link t ...

Exploring various data promises in AngularUI router

I am attempting to utilize the $q service to resolve multiple promises using the $q.all() function with AngularUI router. However, I am encountering issues where it is failing or not functioning as expected. This snippet is from my configuration file that ...

What could be the significance behind these sudden pop-ups of console error messages?

var sendTitle = function() { var title = $("input[name='movie-search-title']").val(); getMovie(title) getQuotes(title) } $("input[name='movie-search-title']").keydown(function(e) { if (e.keyCode == 13) { e.preventDefault(); ...

Storing JSON data in a SQL database

Storing JSON in an MsSql database and passing it to Javascript via a PHP script has been working perfectly. However, when trying to include extra text that is not part of the formatting string, like d, h, a, or p characters, encountered some challenges. Lu ...

"Enhancing Real-Time Communication in Angular with Websockets and $rootScope's Apply

Currently, I am experimenting with an Angular application that utilizes a websocket to interact with the backend. I've encountered some challenges in getting Angular's data binding to function correctly. In this scenario, I have developed a serv ...

Finding documents in MongoDB where the size of an array exceeds 1

Looking to retrieve documents with an array size greater than 1 in my MongoDB collection Here is a snapshot of my collection: { "_id" : ObjectId("5eaaeedd00101108e1123452"), "type" : ["admin","teacher" ...

Angular applications with separate, autonomous routers

Imagine having a massive enterprise application divided into multiple independent submodules (not to be confused with angular modules). I prefer not to overwhelm the routing in a single location and wish for these autonomous modules (non-angular modules) ...

Ways to turn off JavaScript when reaching a certain breakpoint, similar to a media query

I am facing an issue with my <header> and <nav> blocks which are impacted by JavaScript. Is there a way to create a JavaScript solution similar to a media query that would deactivate this JavaScript code if the window width is less than or equa ...

Remove null or empty key-value pairs from a JSONObject

My JSON File Looks Like This: { "models":{}, "path":[ { "path":"/web-profiles", "operations":[ { "type":"", "responseMessages":[] } ] } ], " ...

Is there a way to automatically include a specific date and time in a MySQL Insert query without manually entering it

I need to implement a system in my MySQL database where I can check for the existence of data in a specific table on a daily basis. If the data does not exist after 30 minutes, I want to automatically insert certain data without any manual intervention. ...

I am looking to sort through the data based on the courseCode, but I can't seem to find a way to do it

Here is the JSON data after converting it with res.json() I attempted to filter it based on course code, let's say the code is: 301. I am confused about how to achieve this using JavaScript because of the nested structure. Here is the code snippet I ...

Stop Google Charts from magnifying the view

I'm currently working on creating a column chart using Google Charts. The purpose of this chart is to display the number of pageviews for a specific page within the last 30 days. Below is the JavaScript code I used to create the chart (you can access ...