CSV (Comma-Separated Values) and JSON (JavaScript Object Notation) are both widely used formats for representing data. Converting CSV to JSON is common for tasks like importing or exporting data between systems, APIs, and databases. This tool helps you easily convert your CSV data to JSON format.
In JavaScript, you can easily parse CSV data and convert it to JSON using various libraries or custom logic. Here's an example of how you can handle CSV and JSON in JavaScript:
To convert CSV to JSON, you can use a simple JavaScript function that splits the CSV data into rows and columns and maps it to a JSON format:
function csvToJson(csv) { const lines = csv.split('\n'); const headers = lines[0].split(','); const result = []; 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]; } result.push(obj); } return result; } const csvData = `name,age,city John,30,New York Jane,25,Los Angeles `; console.log(JSON.stringify(csvToJson(csvData), null, 2)); // Converts CSV to JSON
You can validate CSV data by checking the structure of the CSV input before converting it to JSON. Here's a basic example of how to validate if the CSV is correctly formatted:
function validateCsv(csv) { const lines = csv.split('\n'); const headerLength = lines[0].split(',').length; let valid = true; for (let i = 1; i < lines.length; i++) { if (lines[i].split(',').length !== headerLength) { valid = false; break; } } return valid; } const isValidCsv = validateCsv(csvData); // Returns true if CSV is valid, false otherwise console.log(isValidCsv);