Tutorial

How to Convert JSON to CSV with Python: Complete Tutorial with Code Examples

Learn how to convert JSON data to CSV format using Python with complete code examples, handling nested JSON, and best practices for data processing.

2025-10-05
5 min read

🐍 How to Convert JSON to CSV with Python: Complete Tutorial with Code Examples

In daily data processing, we often encounter scenarios where we need to convert JSON format data to CSV tables, such as exporting API data, analyzing log files, or importing into Excel for visualization.

This article will show you how to efficiently convert JSON → CSV using Python, with several common implementation approaches.


📘 1. JSON vs CSV: Key Differences

FeatureJSONCSV
Data StructureTree-like, nestedFlat table
ReadabilityMachine and human readableHuman-friendly, simple structure
Common Use CasesWeb APIs, configuration filesExcel, database import/export
File Extensions.json.csv

When you want to view or analyze JSON data from APIs in spreadsheets, you need to convert it to CSV.


⚙️ 2. Using Python Standard Libraries for JSON to CSV

Python comes with powerful json and csv standard libraries that can handle conversion directly without additional dependencies.

Example 1: Basic Version (Flat JSON Structure)

import json
import csv

# Read JSON file
with open('data.json', 'r', encoding='utf-8') as f:
    data = json.load(f)

# Open CSV file for writing
with open('output.csv', 'w', newline='', encoding='utf-8') as csvfile:
    writer = csv.writer(csvfile)

    # Write headers (extract from first element's keys)
    header = data[0].keys()
    writer.writerow(header)

    # Write each row of data
    for row in data:
        writer.writerow(row.values())

print("✅ JSON successfully converted to CSV: output.csv")

Input Example:

[
  {"name": "Alice", "age": 25, "city": "Shanghai"},
  {"name": "Bob", "age": 30, "city": "Beijing"}
]

Output Result (CSV):

name,age,city
Alice,25,Shanghai
Bob,30,Beijing


🧩 3. Handling Nested JSON

If your JSON contains nested objects or arrays, you need to "flatten" the structure first.

Example 2: Using pandas.json_normalize()

import pandas as pd
import json

# Read nested JSON
with open('nested.json', 'r', encoding='utf-8') as f:
    data = json.load(f)

# Flatten nested structure to flat table
df = pd.json_normalize(data)

# Export to CSV
df.to_csv('output.csv', index=False, encoding='utf-8-sig')

print("✅ Nested JSON successfully converted to CSV: output.csv")

Example Input:

[
  {
    "user": {"name": "Alice", "id": 101},
    "stats": {"score": 98, "level": 3}
  },
  {
    "user": {"name": "Bob", "id": 102},
    "stats": {"score": 87, "level": 2}
  }
]

Output Result:

user.name,user.id,stats.score,stats.level
Alice,101,98,3
Bob,102,87,2

✅ Tip: pandas.json_normalize() automatically flattens nested fields, perfect for complex JSON.


🚀 4. Reading JSON from URL and Exporting to CSV

You can also load JSON data directly from remote APIs:

import requests
import pandas as pd

url = "https://jsonplaceholder.typicode.com/users"
data = requests.get(url).json()

df = pd.json_normalize(data)
df.to_csv('users.csv', index=False, encoding='utf-8-sig')

print("✅ JSON loaded from URL and exported to CSV")


🧠 5. Common Questions (FAQ)

1️⃣ File encoding issues?

→ Use encoding='utf-8-sig' when saving CSV to ensure proper Chinese character display in Excel.

2️⃣ JSON root is not an array?

→ If JSON is a single object (like {}), manually wrap it in an array:

data = [data]

3️⃣ How to import to Excel?

→ In Excel, click "Data" → "From Text/CSV" → select the output file.


🧰 6. Complete Project Example

If you need a command-line tool:

# json2csv.py
import sys
import pandas as pd

def json_to_csv(input_file, output_file):
    df = pd.read_json(input_file)
    df.to_csv(output_file, index=False, encoding='utf-8-sig')
    print(f"✅ {input_file} converted to {output_file}")

if __name__ == "__main__":
    if len(sys.argv) != 3:
        print("Usage: python json2csv.py input.json output.csv")
    else:
        json_to_csv(sys.argv[1], sys.argv[2])

Execute:

python json2csv.py data.json output.csv


🧭 7. Summary

ToolUse CaseAdvantages
csv + jsonSimple JSONStandard library, zero dependencies
pandasNested JSON, large filesPowerful features, batch processing
requestsNetwork dataDirect API fetching

If you only need occasional conversion, you can use our online tool 👉 JsonWork.com/json-to-csv

No Python installation required, supports paste / upload / download, 100% local processing, more secure and convenient.


Published on October 5, 2025
👨‍💻

JsonWork Team

Dedicated to providing developers with the best JSON processing tools

Related Posts

More posts coming soon...

Need Help?