CSV and JSON are two of the most common formats for storing and exchanging data. CSV is ideal for tables and spreadsheets, while JSON is used for APIs and web applications. Understanding both formats and knowing how to convert between them is essential for developers. This article covers the format of each type, conversion algorithms, and practical examples in JavaScript and Python.
CSV format: structure and rules
CSV (Comma-Separated Values) is a text format for representing tabular data. Each line is a record, and fields are separated by a delimiter character.
Delimiters
The standard delimiter is a comma, but different regions and applications use:
- Comma — standard in English-speaking countries
- Semicolon — common in Europe, where the comma is used as a decimal separator
- Tab — TSV (Tab-Separated Values), often used for exports from databases
- Vertical bar — an alternative when the data contains commas and semicolons
name,email,age
Иван Петров,ivan@example.com,30
Мария Сидорова,maria@example.com,25Quoting rules and RFC 4180
RFC 4180 describes the CSV standard:
- Fields containing delimiters, quotes, or line breaks are enclosed in double quotes
- Quotes inside a field are escaped by doubling them:
"He said ""Hello""" - The first row may contain headers (column names)
id,name,description
1,"Иванов, Иван","Строка с ""кавычками"""
2,"Петрова, Мария","Обычное поле"Compatibility issues
Excel and other spreadsheet editors may interpret CSV differently, changing the encoding, delimiters, and quoting rules. When exporting from Excel to CSV, a semicolon is often used in regional settings where a comma is the decimal separator. When importing into other systems, specify the delimiter and encoding explicitly; otherwise, the data may not display correctly.
JSON format: structure and nesting
JSON (JavaScript Object Notation) is a data interchange format based on key-value pairs. It supports arrays, objects, and nested structures.
Arrays of objects
A typical structure for tabular data is an array of objects with the same keys:
[
{"name": "Иван Петров", "email": "ivan@example.com", "age": 30},
{"name": "Мария Сидорова", "email": "maria@example.com", "age": 25}
]Nested data
JSON can store nested objects and arrays, which cannot be represented directly in flat CSV:
{
"user": {
"name": "Иван",
"address": {
"city": "Москва",
"street": "Тверская"
},
"tags": ["admin", "editor"]
}
}CSV vs. JSON: when to use each
| Criterion | CSV | JSON |
|---|---|---|
| Readability | Convenient in Excel and text editors | Convenient in code and APIs |
| Structure | Flat tables only | Nested objects and arrays |
| Size | Usually more compact for tables | Larger because of keys and syntax |
| Typical use | Import/export, reports, analytics | APIs, configurations, web applications |
| Standardization | RFC 4180, but many variations | Strict ECMA-404 standard |
CSV is suitable for working in Excel, importing into CRMs, reports, and simple tables. JSON is suitable for REST APIs, configurations, data exchange between services, and storing structured data in applications. When choosing a format, consider the target system: if the data will be opened in Excel or imported into 1С, choose CSV; if it will be used in a web or mobile application, JSON is usually more convenient.
Converting CSV to JSON
Algorithm
- Read the file line by line
- Determine the delimiter (comma, semicolon, or tab)
- Use the first row as headers (keys)
- For each subsequent row: parse the fields, accounting for quotes, and build an object
- Add the object to an array
Handling edge cases
- Empty fields →
nullor an empty string - Quotes inside fields
- Line breaks inside quotes
- Different encodings (UTF-8, UTF-8 BOM, Windows-1251)
JavaScript: Papa Parse
Papa Parse is a reliable CSV parser for browsers and Node.js:
const Papa = require('papaparse');
const csvString = `name,email,age
Иван Петров,ivan@example.com,30
Мария Сидорова,maria@example.com,25`;
const result = Papa.parse(csvString, {
header: true,
skipEmptyLines: true,
encoding: 'UTF-8'
});
console.log(JSON.stringify(result.data, null, 2));
// [
// {"name": "Иван Петров", "email": "ivan@example.com", "age": "30"},
// {"name": "Мария Сидорова", "email": "maria@example.com", "age": "25"}
// ]JavaScript: manual parsing
For simple CSV without complex quoting, you can avoid using libraries:
function csvToJson(csv) {
const lines = csv.trim().split('\n');
const headers = lines[0].split(',');
return lines.slice(1).map(line => {
const values = line.split(',');
return headers.reduce((obj, header, i) => {
obj[header.trim()] = values[i]?.trim() || '';
return obj;
}, {});
});
}This approach does not account for quotes or commas inside fields—for production use, Papa Parse is a better choice. When parsing CSV with quotes, it is important to track whether the parser is “inside quotes”: commas and line breaks inside quotes must not split a field. Implementing a full parser that complies with RFC 4180 requires a finite-state machine or recursive descent.
Python: csv module
The standard csv module correctly handles RFC 4180:
import csv
import json
def csv_to_json(csv_string):
reader = csv.DictReader(csv_string.splitlines())
return list(reader)
csv_data = """name,email,age
Иван Петров,ivan@example.com,30
Мария Сидорова,maria@example.com,25"""
result = csv_to_json(csv_data)
print(json.dumps(result, ensure_ascii=False, indent=2))Python: pandas
pandas is convenient for large files and analytics:
import pandas as pd
df = pd.read_csv('data.csv', encoding='utf-8-sig')
json_data = df.to_json(orient='records', force_ascii=False)The encoding='utf-8-sig' parameter handles a BOM at the beginning of a file. For files that use a semicolon as the delimiter, specify sep=';'. If there are no headers, pass header=None and set the column names using the names parameter.
Converting JSON to CSV
Flattening nested objects
Nested objects need to be “flattened” into a flat structure. Options include joining keys with a dot (address.city) or storing the nested data as a string.
function flattenObject(obj, prefix = '') {
return Object.keys(obj).reduce((acc, key) => {
const value = obj[key];
const newKey = prefix ? `${prefix}.${key}` : key;
if (value !== null && typeof value === 'object' && !Array.isArray(value)) {
Object.assign(acc, flattenObject(value, newKey));
} else if (Array.isArray(value)) {
acc[newKey] = value.join('; ');
} else {
acc[newKey] = value;
}
return acc;
}, {});
}Handling arrays
Arrays can be converted to a string (using commas or semicolons) or expanded into separate CSV rows. The choice depends on the task. For example, a user's tags, ["admin", "editor"], can be stored as "admin; editor" in a single cell. For arrays of objects (such as a list of orders in a user profile), you will need either to denormalize the data into multiple rows or serialize it as a JSON string inside a cell; the latter makes subsequent work with the data in Excel more difficult.
JavaScript: Papa Parse (reverse conversion)
const jsonData = [
{ name: 'Иван Петров', email: 'ivan@example.com', age: 30 },
{ name: 'Мария Сидорова', email: 'maria@example.com', age: 25 }
];
const csv = Papa.unparse(jsonData);
console.log(csv);
// name,email,age
// Иван Петров,ivan@example.com,30
// Мария Сидорова,maria@example.com,25Python: csv and pandas
import json
import csv
with open('data.json', 'r', encoding='utf-8') as f:
data = json.load(f)
if data:
with open('output.csv', 'w', encoding='utf-8', newline='') as f:
writer = csv.DictWriter(f, fieldnames=data[0].keys())
writer.writeheader()
writer.writerows(data)Using pandas:
import pandas as pd
df = pd.read_json('data.json')
df.to_csv('output.csv', index=False, encoding='utf-8-sig')Common problems and solutions
Encoding and BOM
When saving CSV in UTF-8, Excel adds a BOM (Byte Order Mark) at the beginning of the file. In Python, use encoding='utf-8-sig'; in JavaScript, check for \uFEFF at the beginning of the string.
Compatibility with Excel
For correct display in Excel, use UTF-8 with a BOM and a semicolon as the delimiter in regional settings where the comma is the decimal separator. Some systems expect \r\n at the end of lines.
Large files
For files measured in gigabytes, do not load the entire file into memory. Use stream processing: in Node.js, use fs.createReadStream and a streaming parser; in Python, iterate over lines or use pandas with chunksize. Papa Parse supports streaming through Papa.parse(stream, { stream: true }). In pandas, specify chunksize=10000 when calling read_csv to process the file in chunks. This reduces memory usage and makes it possible to process files larger than the available RAM.
Special characters
In CSV, escape quotes by doubling them. In JSON, escape ", \, line breaks, and tabs. When converting, ensure Unicode is handled correctly. Cyrillic and other non-ASCII characters must be preserved without corruption—always specify UTF-8 when reading and writing files. In Python, use the encoding='utf-8' parameter when opening files; Node.js uses UTF-8 by default, but check the encoding when working with buffers.
Choosing libraries and tools
For working with CSV in JavaScript, Papa Parse remains the most reliable option: it supports streaming, automatic delimiter detection, and correct handling of quotes. Alternatives—csv-parse and fast-csv—are suitable for specific scenarios. In Python, the standard csv module is sufficient for most tasks; pandas adds support for filtering, aggregation, and working with data types. To convert JSON to CSV with nested structures, consider the flatten-json library in Python or write your own flattening function in JavaScript. When choosing a flattening strategy, consider how the data will be used: for importing into Excel, one row per object with flat keys is enough; to load the data back into JSON later, you may need a naming convention for nested fields (for example, user.address.city).
Conclusion
Converting between CSV and JSON is a common task when integrating systems, importing data, and working with APIs. The choice of format depends on the context: tables and reports use CSV, while APIs and web applications use JSON. For reliable conversion, account for encoding, delimiters, quotes, and data size.
For quick conversion without writing code, you can use the online CSV to JSON service, which supports different delimiters and encodings. The service is suitable for one-off conversions, checking data formats, and quickly exporting tables to JSON for use in APIs or configurations.