Skip to content

Edvins Antonovs

Transform CSV string into JSON format JavaScript code challenge

Using JavaScript to transform CSV string into JSON format is a reasonably popular front-end interview code challenge. The code below is the approach I used during my last interview.


Write a function that transforms string in CSV format to JSON. CSV data might look like this:

Initial input

21,john smith,29
32,jane smith,30
59999,sam smith,12

Expected output

Not particulary valid JSON, yet it should look as closer as possible to it.

2 { id: 1, name: 'john smith', age: 29 }
3 { id: 2, name: 'jane smith', age: 30 }

Initial implementation

This code defines a function called csvToJson which takes a single argument, csv. Inside the function, it uses destructuring assignment to split the csv string into two parts: headers and rows. The headers are then split again into an array of individual values using the Array.split() method.

The function then uses the method to iterate over the rows array and for each item it splits the item into an array of individual values using the Array.split() method. It then uses the Array.reduce() method to iterate over the headers array and for each iteration it creates an object with key-value pairs. The key is the header and the value is the corresponding item from the items array.

Finally, the function returns the final array of objects. The code then calls the function and assigns the returned value to jsonData and logs it to the console.

1function csvToJson(csv) {
2 const [headers, ...rows] = csv.split('\n');
3 const headersArr = headers.split(',');
5 return => {
6 const items = item.split(',');
8 return headersArr.reduce((acc, key, index) => {
9 return {
10 ...acc,
11 [key]: items[index],
12 };
13 }, {});
14 });
17const jsonData = csvToJson('id,name,age\n1,john smith,29\n2,jane smith,30');

Potential improvements

  1. Input validation: Add a check to ensure that the input passed to the function is in the correct format (a string in CSV format) and return an error message if it's not.
  2. Handling empty rows: The current implementation will include empty rows in the final JSON output. You can add a check to skip over empty rows before processing them.
  3. Trim values: The current implementation doesn't trim the values in the CSV file which can lead to leading/trailing spaces in the final JSON. You can use the Strim.trim() method to remove these spaces.
  4. Handling quotes and commas inside values: The current implementation assumes that values do not contain commas, if there is a comma inside a value, it will break it into multiple values. You can use a library like Papa Parse to handle this.
  5. Handling special characters: The current implementation doesn't handle special characters, which can lead to errors when trying to parse the JSON. You can use the JSON.stringify() method to handle special characters.
1function csvToJson(csv) {
2 const lines = csv.split('\n').filter((line) => line);
3 const headers = lines
4 .shift()
5 .split(',')
6 .map((header) => header.trim());
8 return => {
9 const items = line.split(',').map((item) => item.trim());
11 return headers.reduce((acc, key, index) => {
12 return {
13 ...acc,
14 [key]: items[index],
15 };
16 }, {});
17 });


© 2024 by Edvins Antonovs. All rights reserved.