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:
1id,name,age21,john smith,2932,jane smith,304...59999,sam smith,12
Not particulary valid JSON, yet it should look as closer as possible to it.
1[2 { id: 1, name: 'john smith', age: 29 }3 { id: 2, name: 'jane smith', age: 30 }4]
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 Array.map()
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(',');4
5 return rows.map((item) => {6 const items = item.split(',');7
8 return headersArr.reduce((acc, key, index) => {9 return {10 ...acc,11 [key]: items[index],12 };13 }, {});14 });15}16
17const jsonData = csvToJson('id,name,age\n1,john smith,29\n2,jane smith,30');18
19console.log(jsonData);
Strim.trim()
method to remove these spaces.JSON.stringify()
method to handle special characters.1function csvToJson(csv) {2 const lines = csv.split('\n').filter((line) => line);3 const headers = lines4 .shift()5 .split(',')6 .map((header) => header.trim());7
8 return lines.map((line) => {9 const items = line.split(',').map((item) => item.trim());10
11 return headers.reduce((acc, key, index) => {12 return {13 ...acc,14 [key]: items[index],15 };16 }, {});17 });18}
Sign up to get updates when I write something new. No spam ever.
Subscribe to my Newsletter