CSV to JSON Converter
an example of a CSV to JSON converter using HTML and JavaScript:
HTML:
php
Copy code
CSV to JSON Converter
JavaScript:
javascript
Copy code
function convertCsvToJson() {
const csvFileInput = document.getElementById('csvFileInput');
const jsonOutput = document.getElementById('jsonOutput');
const file = csvFileInput.files[0];
const reader = new FileReader();
reader.onload = () => {
const lines = reader.result.split('\n');
const headers = lines[0].split(',');
const jsonArray = [];
for (let i = 1; i < lines.length; i++) {
const obj = {};
const currentLine = lines[i].split(',');
for (let j = 0; j < headers.length; j++) {
obj[headers[j]] = currentLine[j];
}
jsonArray.push(obj);
}
jsonOutput.value = JSON.stringify(jsonArray, null, 2);
};
reader.readAsText(file);
}
Explanation:
The HTML code sets up a file input field for the CSV file, a button to trigger the conversion, and a text area to output the resulting JSON.
The JavaScript code defines a convertCsvToJson function that is called when the button is clicked.
The function gets the CSV file from the file input field and reads its contents using the FileReader API.
The function splits the CSV file contents into an array of lines and extracts the headers from the first line.
The function loops through each line of the CSV file (except for the first line) and creates a new object for each row of data, mapping the values to their corresponding headers.
The resulting array of objects is then output as a formatted JSON string to the text area
Comments
Post a Comment