CSV to JSON Converter and Validator

Enter CSV Data

Output

Enter CSV to validate or Convert to JSON

About CSV to JSON Conversion

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.

Why Convert CSV to JSON?

  • Structured Format: JSON provides a structured and hierarchical format, making it easier to work with in applications and APIs.
  • Readability: JSON is human-readable and easier to debug compared to CSV, especially for complex or nested data.
  • Data Interchange: JSON is the preferred format for data interchange between different programming languages and systems, especially with web APIs.
  • Validation: JSON data can be easily validated using various schemas and libraries to ensure it follows the required structure.

Using CSV and JSON in JavaScript

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:

Converting CSV to JSON

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
Validating CSV

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);