How to Convert JSON to CSV (and Back): Complete Guide
Meta Description: Learn how to convert JSON to CSV and CSV to JSON. This guide covers online tools, code examples in JavaScript and Python, and handling nested data.
You have JSON data. You need a spreadsheet. Or vice versa.
This is one of the most common data conversion tasks developers and analysts face. JSON is great for APIs and code; CSV is great for Excel, data analysis, and human review.
Let's cover every way to convert between them.
Why Convert Between JSON and CSV?
JSON to CSV Use Cases
- Export API data to Excel: Make JSON responses analyst-friendly
- Reporting: Turn structured data into rows for pivot tables
- Bulk editing: Easier to edit 1,000 rows in a spreadsheet than JSON
- Data migration: Import JSON data into SQL databases via CSV
- Sharing with non-developers: Not everyone reads JSON
CSV to JSON Use Cases
- Spreadsheet to API: Upload spreadsheet data to web services
- Configuration: Generate JSON config from spreadsheet templates
- Data import: Load CSV exports into NoSQL databases
- Bulk content creation: CSV rows become JSON objects
JSON to CSV: The Basics
Simple Flat JSON → CSV
When your JSON is an array of flat objects, conversion is straightforward:
Input JSON:
[
{ "name": "Alex", "age": 28, "city": "Austin" },
{ "name": "Jordan", "age": 32, "city": "Seattle" },
{ "name": "Taylor", "age": 25, "city": "Denver" }
]
Output CSV:
name,age,city
Alex,28,Austin
Jordan,32,Seattle
Taylor,25,Denver
Each JSON object becomes a row. Each key becomes a column header.
The Challenge: Nested JSON
Real-world JSON is rarely flat:
[
{
"name": "Alex",
"contact": {
"email": "[email protected]",
"phone": "555-1234"
},
"skills": ["Python", "JavaScript", "SQL"]
}
]
CSV is inherently flat—no hierarchy. You have two options:
Option 1: Flatten with dot notation
name,contact.email,contact.phone,skills
Alex,[email protected],555-1234,"Python, JavaScript, SQL"
Option 2: Stringify nested structures
name,contact,skills
Alex,"{""email"":""[email protected]"",""phone"":""555-1234""}","[""Python"",""JavaScript"",""SQL""]"
Option 1 is more usable; Option 2 preserves structure for round-trip conversion.
Using Our Online Converter
Our JSON to CSV converter handles this automatically:
Step 1: Paste Your JSON
Enter your JSON array. The converter validates syntax as you type.
Step 2: Configure Options
- Flatten nested objects: Use dot notation (address.city)
- Array handling: Join with delimiter or create multiple rows
- Headers: Include or exclude column headers
- Delimiter: Comma, tab, semicolon, or custom
Step 3: Download or Copy
Get your CSV file instantly. No data is stored on our servers—conversion happens in your browser.
Programmatic Conversion: JavaScript
Using Built-in Methods
const data = [
{ name: "Alex", age: 28, city: "Austin" },
{ name: "Jordan", age: 32, city: "Seattle" }
];
// Get headers from first object
const headers = Object.keys(data[0]);
// Create CSV rows
const rows = data.map(obj =>
headers.map(header => {
const value = obj[header];
// Escape quotes and wrap in quotes if contains comma
if (typeof value === 'string' && (value.includes(',') || value.includes('"'))) {
return `"${value.replace(/"/g, '""')}"`;
}
return value;
}).join(',')
);
// Combine header and rows
const csv = [headers.join(','), ...rows].join('\n');
console.log(csv);
Using Libraries (Recommended)
For production code, use a library that handles edge cases:
// Using PapaParse (browser & Node.js)
import Papa from 'papaparse';
const json = [
{ name: "Alex", age: 28 },
{ name: "Jordan", age: 32 }
];
const csv = Papa.unparse(json);
console.log(csv);
// name,age
// Alex,28
// Jordan,32
// Using json2csv (Node.js)
import { Parser } from 'json2csv';
const json = [
{ name: "Alex", contact: { email: "[email protected]" } }
];
const parser = new Parser({
fields: ['name', 'contact.email'] // Flatten with dot notation
});
const csv = parser.parse(json);
Programmatic Conversion: Python
Using Built-in csv Module
import csv
import json
data = [
{"name": "Alex", "age": 28, "city": "Austin"},
{"name": "Jordan", "age": 32, "city": "Seattle"}
]
# Write to CSV file
with open('output.csv', 'w', newline='') as f:
writer = csv.DictWriter(f, fieldnames=data[0].keys())
writer.writeheader()
writer.writerows(data)
Using pandas (Recommended)
import pandas as pd
# JSON to CSV
data = [
{"name": "Alex", "age": 28},
{"name": "Jordan", "age": 32}
]
df = pd.DataFrame(data)
df.to_csv('output.csv', index=False)
# With nested JSON - flatten it
nested_data = [
{"name": "Alex", "contact": {"email": "[email protected]"}}
]
df = pd.json_normalize(nested_data) # Flattens nested dicts
df.to_csv('output.csv', index=False)
# Creates columns: name, contact.email
CSV to JSON: Converting Back
Simple CSV → JSON
Input CSV:
name,age,city
Alex,28,Austin
Jordan,32,Seattle
Output JSON:
[
{ "name": "Alex", "age": "28", "city": "Austin" },
{ "name": "Jordan", "age": "32", "city": "Seattle" }
]
Note: CSV values are always strings. You may need to convert types.
Using Our Online Converter
- Paste or upload your CSV
- Configure options (first row as headers, type inference)
- Get formatted JSON output
Programmatic: JavaScript
// Using PapaParse
import Papa from 'papaparse';
const csv = `name,age,city
Alex,28,Austin
Jordan,32,Seattle`;
const result = Papa.parse(csv, {
header: true, // Use first row as keys
dynamicTyping: true // Convert numbers and booleans
});
console.log(result.data);
// [
// { name: "Alex", age: 28, city: "Austin" },
// { name: "Jordan", age: 32, city: "Seattle" }
// ]
Programmatic: Python
import pandas as pd
import json
# CSV to JSON
df = pd.read_csv('input.csv')
json_data = df.to_dict(orient='records')
# Or output as JSON string
json_str = df.to_json(orient='records', indent=2)
Handling Edge Cases
Special Characters
Commas, quotes, and newlines in data need proper escaping:
| Character | CSV Handling |
|---|---|
| Comma | Wrap field in quotes: "Austin, TX" |
| Double quote | Escape with double quote: "She said ""Hello""" |
| Newline | Wrap field in quotes: "Line 1\nLine 2" |
Most libraries handle this automatically. Don't build your own CSV parser—the edge cases will get you.
Large Files
For files over 100MB:
- Streaming: Process line by line instead of loading everything
- Chunking: Use pandas
chunksizeparameter - Workers: Use Web Workers in browser, multiprocessing in Python
# Process large CSV in chunks
for chunk in pd.read_csv('huge.csv', chunksize=10000):
# Process 10,000 rows at a time
process(chunk.to_dict(orient='records'))
Inconsistent Columns
When JSON objects have different keys:
[
{ "name": "Alex", "age": 28 },
{ "name": "Jordan", "city": "Seattle" }
]
Solution: Union all keys, use empty values for missing fields:
name,age,city
Alex,28,
Jordan,,Seattle
Arrays in JSON
Arrays don't map cleanly to CSV. Options:
| Approach | Example | Best When |
|---|---|---|
| Join values | "Python, JavaScript, SQL" |
Human-readable output |
| Multiple rows | Create row per array item | Need to preserve relationships |
| Stringify | "[""Python"",""JavaScript""]" |
Round-trip conversion |
| Multiple columns | skill1,skill2,skill3 |
Fixed-length arrays |
Common Errors and Solutions
Error: "Unexpected token in JSON"
Problem: Your JSON is invalid. Solution: Validate JSON first with our JSON validator.
Error: "Cannot read properties of undefined"
Problem: Inconsistent object structure. Solution: Ensure all objects have the same keys, or handle missing keys.
Error: Garbled characters in CSV
Problem: Encoding mismatch (UTF-8 vs Latin-1).
Solution: Explicitly specify encoding: to_csv('file.csv', encoding='utf-8-sig') for Excel compatibility.
Error: Numbers displayed as text in Excel
Problem: CSV stores everything as text. Solution: Use Excel's "Text to Columns" feature, or import as data connection with type inference.
Convert Your Data Now
Ready to convert?
- JSON to CSV Converter — Transform JSON arrays to spreadsheets
- CSV to JSON Converter — Turn spreadsheets into JSON
- JSON Formatter — Validate and beautify JSON first
All conversions happen in your browser. Your data never touches our servers.
FAQ
Can I convert nested JSON to CSV?
Yes, but you need to flatten it. Nested objects become dot-notation columns (address.city). Arrays can be joined as comma-separated values or expanded into multiple rows. Our converter offers both options.
What's the maximum file size I can convert?
For browser-based tools, typically 50-100MB before performance suffers. For larger files, use a local script with streaming/chunking. Python pandas can handle multi-GB files with the chunksize parameter.
Does converting JSON to CSV lose data?
Potentially, yes. CSV can't represent hierarchical data natively. Arrays get flattened, nested objects get dot-notation keys, and data types (numbers vs strings) aren't preserved. For lossless round-trips, keep the original JSON.
How do I handle dates during conversion?
Dates in JSON are typically ISO 8601 strings ("2026-02-14T12:00:00Z"). They transfer to CSV as strings. Excel may auto-detect them as dates, or you may need to format the column manually.
Can I convert JSON to Excel (XLSX) directly?
CSV is the intermediate step. Convert JSON → CSV, then open in Excel and save as .xlsx. For direct conversion, use libraries like ExcelJS (JavaScript) or openpyxl (Python).
Related Tools:
- JSON to CSV Converter — Convert JSON to CSV
- CSV to JSON Converter — Convert CSV to JSON
- JSON Formatter — Format and validate JSON
- JSON to Excel — Export JSON for spreadsheets