Skip to Content

CSV ⇄ JSON Converter

Convert between CSV and JSON formats with support for various delimiters and formatting options. Perfect for data transformation and API integration.

Examples

CSV Example:

name,age,city
John,30,New York
Jane,25,Los Angeles
Bob,35,Chicago

JSON Example:

[
  {"name": "John", "age": "30", "city": "New York"},
  {"name": "Jane", "age": "25", "city": "Los Angeles"},
  {"name": "Bob", "age": "35", "city": "Chicago"}
]

Key Features

🔄 Bidirectional Conversion

  • CSV to JSON
  • JSON to CSV
  • Automatic format detection

📝 Flexible Delimiter Support

  • Comma (,)
  • Semicolon (;)
  • Tab (\t)
  • Pipe (|)

⚙️ Customizable Options

  • Header row toggle
  • JSON indentation control
  • Formatting preservation

🎯 Multiple Use Cases

  • Data migration
  • API data transformation
  • Excel/Spreadsheet integration
  • Database import/export

CSV Format

CSV (Comma-Separated Values) is a simple text format for storing tabular data.

Basic Structure

name,age,city
John,30,New York
Jane,25,Los Angeles
Bob,35,Chicago

With Different Delimiter

name;age;city
John;30;New York
Jane;25;Los Angeles
Bob;35;Chicago

JSON Format

JSON (JavaScript Object Notation) is a lightweight data interchange format.

Array of Objects

[
{
"name": "John",
"age": "30",
"city": "New York"
},
{
"name": "Jane",
"age": "25",
"city": "Los Angeles"
}
]

Conversion Examples

CSV to JSON

Input (CSV):

id,name,email,role
1,John Doe,john@example.com,Admin
2,Jane Smith,jane@example.com,User
3,Bob Johnson,bob@example.com,Editor

Output (JSON):

[
{
"id": "1",
"name": "John Doe",
"email": "john@example.com",
"role": "Admin"
},
{
"id": "2",
"name": "Jane Smith",
"email": "jane@example.com",
"role": "User"
},
{
"id": "3",
"name": "Bob Johnson",
"email": "bob@example.com",
"role": "Editor"
}
]

JSON to CSV

Input (JSON):

[
{
"product": "Laptop",
"price": 999,
"stock": 15
},
{
"product": "Mouse",
"price": 29,
"stock": 50
}
]

Output (CSV):

product,price,stock
Laptop,999,15
Mouse,29,50

Programming Language Examples

JavaScript

// CSV to JSON
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(',');

headers.forEach((header, index) => {
obj[header.trim()] = currentLine[index]?.trim() || '';
});

result.push(obj);
}

return JSON.stringify(result, null, 2);
}

// JSON to CSV
function jsonToCsv(json) {
const data = JSON.parse(json);
const headers = Object.keys(data[0]);
const csv = [
headers.join(','),
...data.map(row => headers.map(header => row[header]).join(','))
];

return csv.join('\n');
}

// Usage
const csvData = "name,age\nJohn,30\nJane,25";
const jsonData = csvToJson(csvData);
console.log(jsonData);

const jsonString = '[{"name":"John","age":"30"}]';
const csvResult = jsonToCsv(jsonString);
console.log(csvResult);

Python

import csv
import json
from io import StringIO

# CSV to JSON
def csv_to_json(csv_string):
csv_reader = csv.DictReader(StringIO(csv_string))
data = list(csv_reader)
return json.dumps(data, indent=2)

# JSON to CSV
def json_to_csv(json_string):
data = json.loads(json_string)
if not data:
return ""

output = StringIO()
writer = csv.DictWriter(output, fieldnames=data[0].keys())
writer.writeheader()
writer.writerows(data)

return output.getvalue()

# Usage
csv_data = "name,age\nJohn,30\nJane,25"
json_data = csv_to_json(csv_data)
print(json_data)

json_string = '[{"name":"John","age":"30"}]'
csv_result = json_to_csv(json_string)
print(csv_result)

Java

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.csv.CsvMapper;
import com.fasterxml.jackson.dataformat.csv.CsvSchema;

public class CsvJsonConverter {

// CSV to JSON
public static String csvToJson(String csv) throws Exception {
CsvMapper csvMapper = new CsvMapper();
CsvSchema schema = CsvSchema.emptySchema().withHeader();

ObjectMapper objectMapper = new ObjectMapper();
List<?> data = csvMapper
.readerFor(Map.class)
.with(schema)
.readValues(csv)
.readAll();

return objectMapper
.writerWithDefaultPrettyPrinter()
.writeValueAsString(data);
}

// JSON to CSV
public static String jsonToCsv(String json) throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
List<Map<String, Object>> data = objectMapper.readValue(
json,
new TypeReference<List<Map<String, Object>>>() {}
);

CsvMapper csvMapper = new CsvMapper();
CsvSchema.Builder schemaBuilder = CsvSchema.builder();

if (!data.isEmpty()) {
data.get(0).keySet().forEach(schemaBuilder::addColumn);
}

CsvSchema schema = schemaBuilder.build().withHeader();

return csvMapper
.writerFor(List.class)
.with(schema)
.writeValueAsString(data);
}
}

Best Practices

1. Handle Special Characters

CSV files may contain commas, quotes, or newlines within fields. Use proper escaping:

"name","description","price"
"Product A","Contains, commas","$99.99"
"Product B","Contains ""quotes""","$149.99"

2. Validate Data Structure

Before conversion, ensure:

  • CSV has consistent column counts
  • JSON is an array of objects
  • Headers exist in CSV (if expected)
  • All objects have same keys in JSON

3. Choose Appropriate Delimiter

  • Use commas for standard CSV
  • Use semicolons for European locale (where comma is decimal separator)
  • Use tabs for TSV files
  • Use pipes for data with many commas

4. Handle Empty Values

// Check for empty values
const hasEmptyValues = data.some(row =>
Object.values(row).some(value => value === '' || value === null)
);

5. Consider Data Types

CSV stores everything as strings. When converting to JSON, you may need to convert types:

function parseValue(value) {
// Try to parse as number
if (!isNaN(value) && value !== '') {
return Number(value);
}
// Check for boolean
if (value === 'true') return true;
if (value === 'false') return false;
// Return as string
return value;
}

6. Handle Large Files

For large datasets:

  • Use streaming for CSV parsing
  • Process data in chunks
  • Consider memory usage
  • Use appropriate tools (Papa Parse, csv-parser)

Common Use Cases

1. Excel to JSON

Export Excel as CSV, then convert to JSON:

Excel → CSV → JSON

2. API Integration

// Fetch CSV data from API
const response = await fetch('/api/data.csv');
const csvText = await response.text();

// Convert to JSON for processing
const jsonData = csvToJson(csvText);

// Use in application
const data = JSON.parse(jsonData);
data.forEach(item => processItem(item));

3. Database Export/Import

# Export from database to CSV
import sqlite3
import csv

conn = sqlite3.connect('database.db')
cursor = conn.execute('SELECT * FROM users')

with open('users.csv', 'w', newline='') as f:
writer = csv.writer(f)
writer.writerow([description[0] for description in cursor.description])
writer.writerows(cursor.fetchall())

# Convert to JSON for web API
with open('users.csv', 'r') as f:
json_data = csv_to_json(f.read())

with open('users.json', 'w') as f:
f.write(json_data)

4. Data Transformation

// Load CSV
const csvData = fs.readFileSync('input.csv', 'utf-8');

// Convert to JSON
const jsonData = csvToJson(csvData);
const data = JSON.parse(jsonData);

// Transform data
const transformed = data.map(item => ({
...item,
fullName: `${item.firstName} ${item.lastName}`,
age: parseInt(item.age)
}));

// Convert back to CSV if needed
const outputCsv = jsonToCsv(JSON.stringify(transformed));
fs.writeFileSync('output.csv', outputCsv);

FAQ

Q: How do I handle CSV files with quotes and commas? A: Use proper CSV parsing libraries that handle RFC 4180 standard. Fields with special characters should be quoted:

"Name","Value"
"John, Jr.","$1,000"

Q: Can I convert nested JSON to CSV? A: Standard CSV doesn't support nested structures. You need to flatten the data first:

const nested = {name: "John", address: {city: "NYC", zip: "10001"}};
const flat = {name: "John", "address.city": "NYC", "address.zip": "10001"};

Q: What if my JSON objects have different keys? A: Include all unique keys as columns. Missing values will be empty:

name,age,city,country
John,30,NYC,
Jane,25,,USA

Q: How do I preserve data types when converting CSV to JSON? A: CSV stores everything as text. You'll need to manually convert or use a schema:

const schema = {
id: 'number',
name: 'string',
active: 'boolean',
created: 'date'
};

Q: Can I convert CSV with multiple header rows? A: Standard converters expect one header row. For multiple headers, you'll need custom parsing logic.

Q: How do I handle Unicode characters? A: Ensure proper UTF-8 encoding when reading/writing files:

const csvData = fs.readFileSync('data.csv', 'utf-8');