jsondecode.com logo

HomeChevronBlogChevronJSON to CSV: Complete Conversion Guide

Blog post

JSON to CSV: Complete Conversion Guide

Learn how to convert JSON to CSV in JavaScript, Python, and online tools. Step-by-step guide with code examples.

author

Shashank Jain

Author

14/06/20262 minutes 11 seconds read
JSON to CSV: Complete Conversion GuideJSON to CSV: Complete Conversion Guide

Article

Why Convert JSON to CSV?

JSON and CSV serve different purposes. JSON excels at representing nested, hierarchical data. CSV is ideal for flat tabular data — spreadsheets, databases, and data analysis tools like Excel and pandas all prefer CSV. Converting between the two is a common task in data pipelines.

JSON to CSV in JavaScript

The simplest approach for flat JSON arrays:

function jsonToCsv(arr) {
  if (!arr.length) return '';
  const headers = Object.keys(arr[0]);
  const rows = arr.map(obj =>
    headers.map(h => JSON.stringify(obj[h] ?? '')).join(',')
  );
  return [headers.join(','), ...rows].join('\n');
}

const data = [
  { name: 'Alice', age: 30, city: 'New York' },
  { name: 'Bob', age: 25, city: 'London' }
];
console.log(jsonToCsv(data));
// name,age,city
// "Alice",30,"New York"
// "Bob",25,"London"

Handling Nested JSON

Nested objects must be flattened before CSV conversion:

function flatten(obj, prefix = '') {
  return Object.keys(obj).reduce((acc, key) => {
    const val = obj[key];
    const newKey = prefix ? `${prefix}.${key}` : key;
    if (val && typeof val === 'object' && !Array.isArray(val)) {
      Object.assign(acc, flatten(val, newKey));
    } else {
      acc[newKey] = val;
    }
    return acc;
  }, {});
}

const nested = { user: { name: 'Alice', address: { city: 'NYC' } }, age: 30 };
console.log(flatten(nested));
// { 'user.name': 'Alice', 'user.address.city': 'NYC', age: 30 }

JSON to CSV in Python

import csv
import json
import io

def json_to_csv(json_data):
    if isinstance(json_data, str):
        json_data = json.loads(json_data)

    output = io.StringIO()
    writer = csv.DictWriter(output, fieldnames=json_data[0].keys())
    writer.writeheader()
    writer.writerows(json_data)
    return output.getvalue()

data = [{"name": "Alice", "age": 30}, {"name": "Bob", "age": 25}]
print(json_to_csv(data))

Using pandas

import pandas as pd
import json

with open('data.json') as f:
    data = json.load(f)

df = pd.DataFrame(data)
df.to_csv('output.csv', index=False)

Common Pitfalls

ProblemCauseFix
Missing columnsInconsistent keys across objectsCollect all keys first, fill missing with empty string
Comma in valuesUnquoted string fieldsAlways wrap string values in quotes
Nested arrays flattened wrongArrays converted to string representationJoin array values or create separate rows
Unicode issuesDefault encoding mismatchUse encoding='utf-8-sig' for Excel compatibility

FAQ

Can I convert JSON with nested arrays to CSV?

Nested arrays are the hardest case. You have two options: join array items into a delimited string (e.g. pipe-separated), or create one row per array item with repeated parent values. The right choice depends on your downstream tool.

What's the fastest way to convert large JSON files to CSV?

For large files, use streaming. In Python, use ijson to parse incrementally. In Node.js, use streams with the JSONStream package to avoid loading the entire file into memory.

Does jsondecode.com have a JSON to CSV tool?

Yes — use the JSON to CSV converter to paste your JSON and download a CSV instantly, no signup required.

How do I handle null values in CSV?

Represent JSON null as an empty cell (empty string between commas). Most CSV parsers and spreadsheet tools treat empty cells as null/missing values.

What if my JSON is an object, not an array?

If your JSON is a single object (not an array), wrap it: [yourObject]. This produces a single-row CSV. If it's a nested object, flatten it first.

Keep reading

Recent blogs

View all

If jsondecode.com saved you time, share it with your team

Free forever. No ads. No sign-up. Help other developers find it.