JSON to CSV Converter — Developer Code Samples
Convert JSON arrays of objects to CSV format for spreadsheets, data analysis, and ETL pipelines. Python's csv module and json module together handle this conversion without any external dependencies. jq is the command-line tool of choice for shell pipelines.
Try the interactive version online:
Open JSON to CSV Converter Tool →
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
| json_string | str | Yes | JSON string containing an array of objects |
| delimiter | str | No | Field separator character (default: comma) |
| include_headers | bool | No | Include header row with column names (default: True) |
Returns: CSV-formatted string with header row and data rows
Code Examples
import json
import csv
import io
def json_to_csv(json_string, delimiter=','):
"""Convert a JSON array of objects to CSV string."""
data = json.loads(json_string)
if not data:
return ""
# Handle both array and object with array value
if isinstance(data, dict):
# Find first array value
for v in data.values():
if isinstance(v, list):
data = v
break
if not isinstance(data, list):
raise ValueError("JSON must be an array of objects")
# Collect all keys (headers) in order of first appearance
headers = []
seen = set()
for row in data:
if isinstance(row, dict):
for k in row.keys():
if k not in seen:
headers.append(k)
seen.add(k)
# Write CSV to string buffer
output = io.StringIO()
writer = csv.DictWriter(output, fieldnames=headers, delimiter=delimiter,
extrasaction='ignore', lineterminator='\n')
writer.writeheader()
writer.writerows(data)
return output.getvalue()
# Example
json_data = '''[
{"name": "Alice", "age": 30, "city": "New York"},
{"name": "Bob", "age": 25, "city": "London"},
{"name": "Carol", "age": 35, "city": "Tokyo"}
]'''
csv_output = json_to_csv(json_data)
print(csv_output)
# Output:
# name,age,city
# Alice,30,New York
# Bob,25,London
# Carol,35,Tokyo
# Write to file
with open('output.csv', 'w', newline='', encoding='utf-8') as f:
f.write(csv_output)