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.