티스토리 뷰
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!
'AngularJS' 카테고리의 다른 글
AngularJS: Validating Data Before Updating the API (0) | 2023.09.30 |
---|---|
AngularJS: Importing CSV Files and Save Each Row (0) | 2023.09.01 |
AngularJS: Dealing with Async Updates using Promise.all() and $scope.$applyAsync() (0) | 2023.08.01 |
AngularJS: Handling Null and Empty Values with orderBy Filter (0) | 2023.07.26 |
Introducing AngularJS and Analyzing the MVC Architecture (0) | 2023.05.19 |
- Total
- Today
- Yesterday
- SSR
- scrollabe table
- CSR
- orderByFilter
- responsive table
- Bootstrap5 tab
- $scope.$applyAsync()
- Next.js
- responsive design
- handleNullData
- CSV Validation
- Responsive Troubleshooting
- junior frontend developer
- CSS white space issue
- ImportCSV
- frontend
- UX
- promise.all()
- developer tools
- angularjs
- BEM-like-Naming
- BEM
- JSON-CSV-Conversion
- CSS
- React.js
- Desk Setup
- bootstrap5
- #노개북 #노마드코더 #개발자북클럽 #클린코드
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 | 30 | 31 |