Calculators Converters Generators Developer Tools Finance Tools Writing Tools SEO Tools Image Tools Network Tools Productivity Tools Social Media Tools
Blog About Contact
Dev ToolsJune 3, 20267 min read

How to Convert JSON to CSV in Python: 3 Easy Methods

How to Convert JSON to CSV in Python: 3 Easy Methods

You have a JSON file or an API response, and you need it as a CSV - maybe to open in Excel, load into a database, or hand to a teammate who lives in spreadsheets. Converting JSON to CSV in Python is a five-minute task once you know which tool to reach for, but the right approach depends on whether your data is flat or nested. This guide walks through three reliable methods, from a single line of pandas to the built-in standard library, with copy-paste code for each. By the end, you will know exactly which method fits your data and how to avoid the two mistakes that quietly corrupt CSV output.

Why Convert JSON to CSV in Python?

JSON (JavaScript Object Notation) is the standard format for APIs and web data because it represents nested, hierarchical structures cleanly. CSV (comma-separated values) is the universal tabular format - flat rows and columns that every spreadsheet, database, and analytics tool can read. The two formats serve different worlds, so converting between them is one of the most common data-wrangling tasks in Python.

Python is especially well suited to this job. The json and csv modules are both part of the standard library, meaning they ship with Python and require no installation. For more complex data, the pandas library turns the entire conversion into a single line. The catch is that JSON can be nested while CSV is strictly flat, so the moment your data has objects inside objects, you need a method that flattens it correctly - which is exactly what we cover below.

How to Convert JSON to CSV in Python - Step by Step

Here are three methods, ordered from simplest to most flexible. Pick based on your data shape and whether you already use pandas.

Method 1 - pandas (easiest for most cases)

If your JSON is a list of records, pandas converts it in two lines. Install pandas first with pip install pandas, then:

import pandas as pd df = pd.read_json("data.json") df.to_csv("output.csv", index=False)

The index=False argument stops pandas from writing the row numbers as an extra column. This method is the go-to for flat data and handles type conversion automatically.

Method 2 - Standard library (no dependencies)

When you cannot install pandas, the built-in json and csv modules do the job:

import json import csv with open("data.json") as f: data = json.load(f) with open("output.csv", "w", newline="") as f: writer = csv.DictWriter(f, fieldnames=data[0].keys()) writer.writeheader() writer.writerows(data)

The csv.DictWriter takes the keys from the first object as the header row, then writes each dictionary as a row. The newline="" argument prevents blank lines between rows on Windows - a classic gotcha.

Method 3 - Nested JSON with json_normalize

If your JSON has nested objects, use pandas' json_normalize to flatten them into dot-notation columns:

import pandas as pd import json with open("data.json") as f: data = json.load(f) df = pd.json_normalize(data) df.to_csv("output.csv", index=False)

A nested field like address.city becomes its own column automatically. This is the method to use whenever your data is not perfectly flat.

→ Need a quick one-off conversion without writing code? Use our free JSON to CSV Converter at GlobalUtilityHub to convert and download instantly - no sign-up needed.

Worked Example: Converting an API Response

Say you pulled a list of users from an API and saved it as users.json:

[ {"id": 1, "name": "Alice", "email": "alice@example.com"}, {"id": 2, "name": "Bob", "email": "bob@example.com"}, {"id": 3, "name": "Carol", "email": "carol@example.com"} ]

Running Method 1 (pandas) on this file:

import pandas as pd df = pd.read_json("users.json") df.to_csv("users.csv", index=False)

Produces users.csv:

id,name,email 1,Alice,alice@example.com 2,Bob,bob@example.com 3,Carol,carol@example.com

Three lines of code, and the data is ready to open in Excel or import into a database. If the JSON had a nested field - say each user had an address object - you would swap in pd.json_normalize and get address.city and address.zip columns automatically.

Python JSON-to-CSV Methods Compared

Each method has a sweet spot. This table helps you choose quickly.

MethodInstall needed?Handles nesting?Lines of codeBest for
pandas (read_json)Yes (pip install pandas)Partially2Flat data, existing pandas users
csv.DictWriterNo (built-in)No~7No-dependency environments
json_normalizeYes (pandas)Yes (dot notation)4Nested JSON
Online converterNoYes0One-off conversions

Common Mistakes to Avoid

* Forgetting newline="" on Windows. When using the built-in csv module, omitting newline="" in the open() call inserts a blank line between every row on Windows. Always include it when writing CSV files.

* Trying to write nested JSON with csv.DictWriter. The standard csv module cannot flatten nested objects - it will write the entire nested dictionary as messy text in one cell. For nested data, use pd.json_normalize instead.

* Losing leading zeros on identifiers. pandas may interpret a ZIP code like "01234" as the number 1234, dropping the leading zero. Force string types with pd.read_json("data.json", dtype=str) or specify dtypes per column when identifiers matter.

* Assuming the JSON is a list. If your JSON is wrapped in an outer object like {"results": [...]}, you must extract the inner list first with data["results"] before converting, or pandas will not produce clean rows.

Handling Special Characters and Encoding

Real-world data is messy. Names contain accents, descriptions contain commas and quotes, and international data brings characters far outside the basic English alphabet. Getting encoding right is what separates a clean export from a file full of garbled symbols.

Always write your CSV as UTF-8, the universal text encoding. With pandas, this is the default, but you can be explicit:

df.to_csv("output.csv", index=False, encoding="utf-8")

There is one important caveat with Microsoft Excel. Older versions of Excel do not automatically detect UTF-8, so characters like é, ñ, or 中文 appear as mojibake (random symbols). The fix is to add a byte-order mark (BOM) that signals UTF-8 to Excel:

df.to_csv("output.csv", index=False, encoding="utf-8-sig")

The "sig" variant writes the same UTF-8 data but prepends the BOM, and Excel then displays special characters correctly. Values containing commas, quotes, or line breaks are handled automatically by both pandas and the csv module - they wrap such fields in double quotes following the CSV standard (RFC 4180), so you do not need to escape them manually. If you build CSV by hand with string concatenation instead of a proper library, you will eventually corrupt a row this way, which is the strongest reason to always use csv or pandas rather than f-strings.

Converting Large JSON Files Efficiently

When your JSON file is large - hundreds of megabytes or millions of records - loading the entire thing into memory at once can exhaust your RAM and crash the script. The naive json.load() reads everything into memory before you can write a single row.

For large but manageable files, pandas remains efficient because it uses optimized C code under the hood:

import pandas as pd df = pd.read_json("large_data.json") df.to_csv("output.csv", index=False)

For truly massive files that do not fit in memory, process the data in chunks. If your JSON is in newline-delimited format (one JSON object per line, common in data exports and logs), you can stream it line by line:

import json import csv with open("huge.jsonl") as infile, open("output.csv", "w", newline="") as outfile: writer = None for line in infile: record = json.loads(line) if writer is None: writer = csv.DictWriter(outfile, fieldnames=record.keys()) writer.writeheader() writer.writerow(record)

This streaming approach reads and writes one record at a time, keeping memory usage flat regardless of file size. It is the standard technique for converting large datasets. For repeated large-scale conversions, also consider whether a database or a tool like DuckDB might serve you better than flat-file conversion - but for most one-time jobs, chunked or pandas-based conversion is plenty.

Converting JSON to CSV from the Command Line

Sometimes you do not want to open a Python file at all - you just need a quick conversion in the terminal, perhaps inside a shell script or a data pipeline. The command-line tool jq is purpose-built for processing JSON and can output CSV directly. It is available on macOS, Linux, and Windows.

For a JSON array of flat objects, this one-liner produces a CSV with a header row:

jq -r '(.[0] | keys_unsorted) as $keys | $keys, (.[] | [.[ $keys[] ]]) | @csv' data.json > output.csv

Breaking that down: it grabs the keys from the first object to build the header, then maps each object's values in the same key order, and the @csv filter formats everything as properly quoted CSV. The -r flag outputs raw text rather than JSON-encoded strings.

For simpler cases where you know your column names, an explicit version is easier to read:

jq -r '["id","name","email"], (.[] | [.id, .name, .email]) | @csv' data.json

The jq approach shines in automation - cron jobs, CI pipelines, and shell scripts - where spinning up Python would be overkill. For interactive work or complex nested data, Python's pandas is still more flexible, but for a quick scripted conversion, jq is hard to beat. Choose the tool that matches the context: jq for the terminal, pandas for notebooks and applications, and an online converter for one-off manual jobs.

The Bottom Line

Converting JSON to CSV in Python comes down to three tools: pandas for flat data (two lines), json_normalize for nested data (four lines), and the built-in csv module when you cannot install anything. Match the method to your data shape, remember newline="" on Windows, and protect your leading zeros, and you will get clean CSV every time.

For a quick conversion without opening your editor, our JSON to CSV Converter gives you the result in under 30 seconds - try it free at globalutilityhub.com/converters/json-to-csv/.

✍️ Written by the GlobalUtilityHub Editorial Team|📅 Last reviewed: June 2026|Fact-checked for accuracy
Ready to try it yourself?

Use our free JSON to CSV Converter to apply what you have learned.

Open JSON to CSV Converter

Frequently Asked Questions

The easiest way is using pandas: pd.read_json('data.json').to_csv('output.csv', index=False). This two-line approach handles most flat JSON files automatically, including type conversion. Install pandas first with pip install pandas. If you cannot install packages, the built-in csv.DictWriter achieves the same in about seven lines using only the standard library.
Use pandas' json_normalize function, which flattens nested objects into columns with dot-notation names. Load your JSON with the json module, then call pd.json_normalize(data) and write the result with to_csv(). A nested field like address.city becomes a column automatically. The standard csv module cannot do this.
No. Python's standard library includes both the json and csv modules, which require no installation. Use json.load() to read the data and csv.DictWriter to write it. pandas is more convenient and handles nesting and type conversion better, but it is optional. For environments where you cannot install packages, the standard library is fully capable for flat data.
If you have JSON as a string variable rather than a file, parse it first with json.loads(your_string), then proceed with either pandas or the csv module. With pandas you can also use pd.read_json(StringIO(your_string)). The conversion logic is identical once the string is parsed into a Python list or dictionary.
Dictionary key order determines column order. In Python 3.7+, dictionaries preserve insertion order, so columns follow the order keys appear in your JSON. If you need a specific column order, pass an explicit fieldnames list to csv.DictWriter, or reorder the pandas DataFrame columns before writing.
pandas handles this gracefully - it creates a column for every key found and fills missing values with NaN. With the built-in csv module, collect all unique keys first using a set across all objects, pass them as fieldnames, and set restval to handle missing keys. pandas is much easier for inconsistent data.
Yes. With pandas: pd.read_csv('data.csv').to_json('output.json', orient='records'). The orient='records' argument produces an array of objects. With the standard library, use csv.DictReader to read rows as dictionaries, then json.dump() to write them out.
Use UTF-8 by specifying encoding='utf-8' in your open() call. If the CSV will be opened in older versions of Excel that misread UTF-8, use encoding='utf-8-sig' instead - the sig adds a byte-order mark that tells Excel to interpret the file as UTF-8, preventing garbled characters.