In this approach, we will input the contents of the CSV file in an array and split the content of the array based on a delimiter. All the rows of the CSV will be converted to JSON objects which will be added to the resultant array which will then be converted to JSON and a corresponding JSON output file will be generated.
Follow the steps below to achieve the solution:
- Read the csv file using default fs npm package.
- Convert the data to String and split it in an array.
- Generate a headers array.
- For all the remaining n-1 rows do the following:
- Create an empty object to add values of current row to it.
- Declare a string str as current array value to change the delimiter and store the generated string in a new string s.
- If we encounter opening quote (“) then we keep commas as it is otherwise we replace them with pipe “|”
- Keep adding the characters we traverse to a String s.
- Split the string using pipe delimiter | and store the values in a properties array.
- For each header, if the value contains multiple comma separated data, then we store it in the form of array otherwise directly the value is stored.
- Add the generated object to our result array.
- Convert the resultant array to json and generate the JSON output file.
- How to create comma separated list from an array in PHP ?
- Export JSON to CSV file in Angular
- Nodejs | Automatic restart NodeJs server with nodemon
- How to convert an array to CSV file in PHP ?
- JSON | modify an array value of a JSON object
- Writing a CSV file in Java using OpenCSV
- How to download a CSV file in PHP that is triggered through a URL ?
- How to import data from .CSV file into MySQL table using Node.js ?
- Split a comma delimited string into an array in PHP
- How to read and write JSON file using Node.js ?
- How to update dependency in package.json file ?
- How to create a dynamic JSON file by fetching data from localserver database ?
- How to work with Node.js and JSON file ?
- How to fetch data from JSON file and display in HTML table using jQuery ?
- How to send data of HTML form directly to JSON file?
- How to append data in JSON file through HTML form using PHP ?
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.