티스토리 뷰

Today, I want to dive into an intriguing method that I've employed while working with the transition between CSV and JSON formats. As developers, we often encounter situations where data needs to be stored, processed, and then retrieved in a convenient format. In this blog post, I'm going to outline a technique that makes storing and retrieving data in a CSV format from a JSON object a seamless process. 

When I was assigned this task, I was wondering why not just upload and store the CSV file in the system? So I did some research, and I learned that storing data in the JSON format in our database rather than as raw CSV files provides a multitude of advantages: 


1. Readability and Structure: JSON format is both human-readable and easy to parse, making the stored data easily understandable and workable. 
2. Flexibility: JSON's structure allows for nested objects and arrays, making it a more flexible data representation.
3. Standardized Data Interchange: Many modern APIs use JSON for data interchange, making it the lingua franca of web-based data.
4. Storage Efficiency: When storing data in a structured database, JSON can often be more space-efficient than CSV, especially when there are many optional columns in your data.
5. Security: Parsing CSV is prone to injection attacks if not done carefully, while JSON parsing libraries are typically more robust and safe.

1. Converting JSON to CSV

Before diving into the downloading part, let's first convert our JSON data to CSV. This function aptly named `jsonToCSV` takes care of that:

function jsonToCSV(objArray) {
    const array = typeof objArray !== 'object' ? JSON.parse(objArray) : objArray;
    let csvString = '';
    
    if (array.length > 0) {
        const headers = Object.keys(array[0]).join(',');
        csvString += headers + '\r\n';
    }
    
    for (let item of array) {
        let line = '';
        for (let key in item) {
            if (line) line += ',';
            line += String(item[key]).includes(',') ? `"${item[key]}"` : item[key];
        }
        csvString += line + '\r\n';
    }
    return csvString;
}

 

The logic is quite simple: 
- We first ensure that the data we have is an array of objects.
- We extract the headers (i.e., object keys) and append them as the first row of our CSV string.
- We then iterate over each object (row of data) and append its values to our CSV string, ensuring that data containing commas is wrapped in double quotes.

2. Fetching Data and Prompting a Download

Now, with our CSV string in hand, it's time to download the data. Here's an example function, integrated with AngularJS, that fetches JSON data from an API, converts it to CSV, and initiates a download:

$scope.downloadSampleCSV = function () {
    $http.get('/api/Settings/User/SystemDefaults/Your CSV')
        .then(function(response) {
            const jsonData = response.data;
            const csvContent = jsonToCSV(jsonData);
            $scope.downloadCSV(csvContent, 'Sample.csv');
        });
};

 

The function:
- Sends a GET request to fetch JSON data.
- Uses the `jsonToCSV` function to convert this data to CSV.
- Calls another function (in this example, `$scope.downloadCSV`) to handle the CSV download. 



Happy coding!