Convert JSON to CSV: Complete Guide
Convert JSON to CSV easily! Learn how to transform JSON data into CSV format using JavaScript, Python, and online tools. Perfect for Excel imports and data analysis.
Why Convert JSON to CSV?
CSV (Comma-Separated Values) format is widely supported by spreadsheet applications like Excel, Google Sheets, and data analysis tools. Converting JSON to CSV allows you to:
- Import data into Excel or Google Sheets
- Analyze data with traditional spreadsheet tools
- Share data with non-technical users
- Reduce file size for simple tabular data
Converting JSON to CSV in JavaScript
Simple Array of Objects
function jsonToCSV(jsonData) {
// Get headers from first object
const headers = Object.keys(jsonData[0]);
// Create header row
let csv = headers.join(',') + '\\n';
// Add data rows
jsonData.forEach(obj => {
const row = headers.map(header => {
const value = obj[header];
// Escape commas and quotes
if (typeof value === 'string' && (value.includes(',') || value.includes('"'))) {
return `"${value.replace(/"/g, '""')}"`;
}
return value;
});
csv += row.join(',') + '\\n';
});
return csv;
}
// Example usage
const data = [
{ name: "John", age: 30, city: "New York" },
{ name: "Jane", age: 25, city: "Los Angeles" }
];
const csv = jsonToCSV(data);
console.log(csv);
/*
name,age,city
John,30,New York
Jane,25,Los Angeles
*/
Download CSV File in Browser
function downloadCSV(jsonData, filename = 'data.csv') {
const csv = jsonToCSV(jsonData);
const blob = new Blob([csv], { type: 'text/csv' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
a.click();
URL.revokeObjectURL(url);
}
Converting JSON to CSV in Python
Using csv Module
import json
import csv
def json_to_csv(json_file, csv_file):
# Read JSON
with open(json_file, 'r') as f:
data = json.load(f)
# Write CSV
with open(csv_file, 'w', newline='') as f:
if data:
writer = csv.DictWriter(f, fieldnames=data[0].keys())
writer.writeheader()
writer.writerows(data)
# Usage
json_to_csv('input.json', 'output.csv')
Using pandas (Recommended)
import pandas as pd
# Read JSON
df = pd.read_json('data.json')
# Convert to CSV
df.to_csv('output.csv', index=False)
# Or from JSON string
import json
json_data = '[{"name":"John","age":30},{"name":"Jane","age":25}]'
df = pd.DataFrame(json.loads(json_data))
df.to_csv('output.csv', index=False)
Handling Nested JSON
Flattening Nested Objects
function flattenJSON(obj, prefix = '') {
const flattened = {};
for (const key in obj) {
const newKey = prefix ? `${prefix}.${key}` : key;
if (typeof obj[key] === 'object' && obj[key] !== null && !Array.isArray(obj[key])) {
Object.assign(flattened, flattenJSON(obj[key], newKey));
} else if (Array.isArray(obj[key])) {
flattened[newKey] = JSON.stringify(obj[key]);
} else {
flattened[newKey] = obj[key];
}
}
return flattened;
}
const nested = {
name: "John",
address: {
city: "New York",
zip: "10001"
}
};
console.log(flattenJSON(nested));
// { name: "John", "address.city": "New York", "address.zip": "10001" }
Free Tool: Use our JSON Analytics tool to convert and export your JSON data to CSV format instantly!
Online JSON to CSV Converters
For quick conversions without coding, you can use online tools like JSONXPath:
- Paste or upload your JSON data
- Visualize and validate the structure
- Export analytics to CSV format
- 100% browser-based (data never leaves your device)
Common Issues and Solutions
Handling Special Characters
// Always escape commas, quotes, and newlines
function escapeCSVValue(value) {
if (value == null) return '';
const stringValue = String(value);
// If contains comma, quote, or newline, wrap in quotes
if (stringValue.includes(',') || stringValue.includes('"') || stringValue.includes('\\n')) {
return `"${stringValue.replace(/"/g, '""')}"`;
}
return stringValue;
}
Summary
- JSON to CSV conversion is useful for Excel imports and data analysis
- JavaScript: Use custom functions or libraries for browser-based conversion
- Python: Use pandas for easy conversion with one line of code
- Always handle special characters (commas, quotes, newlines)
- Flatten nested JSON objects before conversion