Welcome folks today in this blog post we will be parsing csv
files and export it to json
file using the papa parse
library in browser. All the full source code of the application is shown below.
Get Started
In order to get started you need to make an index.html
file and copy paste the following code
index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<!DOCTYPE html> <html> <head> <title>CSV to JSON Converter</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/PapaParse/5.3.0/papaparse.min.js"></script> </head> <body> <input type="file" id="csv-file" accept=".csv" /> <br><br> <button id="convert-btn">Convert to JSON</button> <br><br> <a id="download-link" style="display: none" download="data.json">Download JSON</a> </body> </html> |
As you can see we are including the cdn
of the papaparse library and then we have the input
field where we allow the user to select the csv
file and then we have the button to export to json
file and download it as attachment in browser. Now we need to define the javascript
code as shown below
index.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
const csvFile = document.getElementById('csv-file'); const convertBtn = document.getElementById('convert-btn'); const downloadLink = document.getElementById('download-link'); let data = null; csvFile.addEventListener('change', (e) => { const file = e.target.files[0]; Papa.parse(file, { header: true, complete: (results) => { data = results.data; console.log('Data parsed:', data); }, error: (error) => { console.log(error); } }); }); convertBtn.addEventListener('click', () => { if (data) { const jsonData = JSON.stringify(data); const blob = new Blob([jsonData], {type: 'application/json'}); const url = URL.createObjectURL(blob); downloadLink.setAttribute('href', url); downloadLink.style.display = 'block'; } }); |
As you can see we are parsing the selected csv
file and then we are exporting the contents of the csv
file to the json file using the JSON.stringify()
method and then we are converting it to blob
and download it as attachment.