+ 4
How to convert CSV file to nested JSON file in Node.js?
Is it possible to convert CSV file to nested JSON file in Node.js?🤔 I tried various ways with csvtojson Node.js module and I wasn't successful.🫢 With this code below you can see sample CSV data and desired JSON result. Please guide me or give me some tips.🙌 https://code.sololearn.com/cAIq7vh8rFYd/?ref=app
2 odpowiedzi
+ 6
If you can make a couple of reasonable assumptions about your CSV structure, you can get away with vanilla JavaScript. The string.split() method is the simplest way to get the column values, if the separator is known, and there is no text field enclosed in quotes which might contain a separator character.
The string array can be destrucured to meaningfully named variables, which represent the column headings.
Then you can construct the JSON object which is supposed to have a rigid structure just the same as the CSV.
From your example it seems the CSV contains less data than the JSON. So where is the rest coming from? Hardcoded?
Example for single line:
https://code.sololearn.com/cQC9Wgwzxv1M/?ref=app
If this doesn't work out, recently I used a library called Papa Parse that is very convenient for reading CSV files. More info here:
https://www.sololearn.com/post/1415338/?ref=app
+ 5
Tibor Santa Hi Tib, thanks for your effort with reply.
Your approach in your code looks nice but I don't know if csv file remains in the same format because columns could be added or deleted. Separator will be always ; but maybe this char will be in description column as you mentioned 🤔
Yes, csv doesn't contain all data and many columns are as you guessed right - hardcoded.
Well, I try to choose your approach first because I love the simplicity. ❤️