Convert JSON to CSV: Nested Data, Nulls and Checks

Convert JSON to CSV with a tested Python example for nested values, later keys and decimals. Check the output and understand null and spreadsheet limits.

Updated · Markdown version

To convert JSON to CSV reliably, decide what one row represents, collect columns from all records and choose how to represent nested values and missing data. The example below converts an array of objects into UTF-8 CSV. Nested objects and arrays stay as JSON text inside a cell, rather than being silently flattened or expanded into extra rows.

Choose a conversion policy before writing the CSV

Input situationPolicy in this exampleWhen you need a different workflow
Top-level array of objectsOne CSV row per objectA wrapper such as results needs an explicit extraction step
Keys appear in later rowsUnion of all keys, first-seen column orderA receiving system may require an explicit fixed schema
Nested object or arrayCompact JSON in one cellAn import may require selected nested fields as columns
Null, missing key or empty stringAll appear as an empty cellKeep JSON or define a collision-checked encoding if distinctions matter
Decimal numberParsed with Decimal and written as decimal textSpreadsheet import can still reinterpret or round it

This is a documented exchange format, not a lossless JSON replacement. Keep the original. A successful conversion does not prove an external application's import will preserve types.

Prepare a complete, realistic example

You need Python 3 and permission to read the source file and create the chosen output. The helper runs locally with the standard library and makes no network requests. Do not paste customer data into an AI chat merely to perform this conversion.

Save this as data.json in a new folder:

[
  {"id":"00123","active":true,"amount":1.10,"address":{"city":"Austin"},"note":"Austin, TX"},
  {"id":"00124","active":false,"amount":null,"tags":["new","trial"],"note":""}
]

Expected columns are id,active,amount,address,note,tags. There are two data rows. The leading-zero ID stays a string in the CSV file, active uses lowercase true/false, the first amount is 1.10, and the later tags key is included. The absent address and null amount in row two become empty cells under this policy.

For this input, the decoded first address cell is {"city":"Austin"}. Its on-disk CSV representation contains extra double quotes because CSV quotes and escapes a cell containing JSON quotes. Use a CSV reader to check values; do not count commas or physical lines to count records.

Run a converter whose behavior matches the instructions

Give your agent this request if it is helping with a different export:

Inspect the supplied JSON shape and propose the row and nested-field policy.
Do not upload the file, infer missing values or overwrite the source.
Use all records to determine columns. Preserve string IDs and decimal text.
Explain which source distinctions the chosen CSV format loses.
Produce a local output and verify its parsed rows against the input policy.

Save the following as json_to_csv.py. It refuses duplicate keys, nonfinite JSON numbers, an unsupported top-level shape and common formula-like string prefixes. It validates before opening the output and refuses to replace an existing file. Its teaching limits are 2 MiB, 10,000 records and 500 columns.

"""Bounded offline conversion: union of columns, JSON cells for nested values."""
import csv
import io
import json
import sys
from decimal import Decimal


def reject_constant(_):
    raise ValueError('nonfinite number is not valid input')


def unique_object(pairs):
    result = {}
    for key, value in pairs:
        if key in result:
            raise ValueError('duplicate JSON key')
        result[key] = value
    return result


def encoded(value):
    if value is None:
        return 'null'
    if isinstance(value, bool):
        return 'true' if value else 'false'
    if isinstance(value, (int, Decimal)):
        return str(value)
    if isinstance(value, str):
        return json.dumps(value, ensure_ascii=False)
    if isinstance(value, list):
        return '[' + ','.join(encoded(v) for v in value) + ']'
    return '{' + ','.join(json.dumps(k, ensure_ascii=False) + ':' + encoded(v) for k, v in value.items()) + '}'


def cell(value):
    if value is None:
        return ''
    if isinstance(value, str):
        # Basic stop for common spreadsheet formula prefixes, not a security certification.
        if value.lstrip().startswith(('=', '+', '-', '@')) or value.startswith(('\t', '\r', '\n')):
            raise ValueError('formula-like string: choose a reviewed spreadsheet policy before converting')
        return value
    return encoded(value)


def convert(source):
    with open(source, 'rb') as stream:
        raw = stream.read(2 * 1024 * 1024 + 1)
    if len(raw) > 2 * 1024 * 1024:
        raise ValueError('example input cap is 2 MiB')
    rows = json.loads(raw.decode('utf-8-sig'), parse_float=Decimal,
                      parse_constant=reject_constant, object_pairs_hook=unique_object)
    if not isinstance(rows, list) or not 1 <= len(rows) <= 10000 or not all(isinstance(r, dict) for r in rows):
        raise ValueError('expected a nonempty array of at most 10000 objects')
    columns = list(dict.fromkeys(k for row in rows for k in row))
    if not 1 <= len(columns) <= 500 or any(not k or cell(k) != k for k in columns):
        raise ValueError('expected 1 to 500 nonempty column names')
    converted = [{k: cell(v) for k, v in row.items()} for row in rows]
    buffer = io.StringIO(newline='')
    writer = csv.DictWriter(buffer, fieldnames=columns, restval='', extrasaction='raise')
    writer.writeheader()
    writer.writerows(converted)
    return buffer.getvalue(), len(rows), columns


def main():
    try:
        if len(sys.argv) != 3:
            raise ValueError('usage: json_to_csv.py input.json output.csv')
        text, count, columns = convert(sys.argv[1])
        with open(sys.argv[2], 'x', encoding='utf-8', newline='') as stream:
            stream.write(text)
        print(json.dumps({'rows': count, 'columns': columns, 'nested_policy': 'JSON cell', 'null_missing_empty_distinct': False}))
        return 0
    except (OSError, ValueError, UnicodeError, ArithmeticError, RecursionError) as exc:
        print(json.dumps({'error': str(exc)}))
        return 2


if __name__ == '__main__':
    sys.exit(main())

On Windows PowerShell:

py -3 -I .\json_to_csv.py .\data.json .\out.csv

On macOS or Linux:

python3 -I json_to_csv.py data.json out.csv

Use your installed Python command if necessary. Expect a summary with two rows, six columns, nested_policy: "JSON cell" and null_missing_empty_distinct: false. That last field deliberately discloses a limitation; it is not an error.

Python's csv documentation describes column ordering, quoting and the newline setting used here. Its JSON documentation documents decoder hooks used to reject duplicate keys and nonfinite constants. The script's policy choices are ours, not requirements of the CSV format.

Verify the parsed output, not just its appearance

Save this as check_output.py beside the generated file:

import csv
import json
with open("out.csv", encoding="utf-8", newline="") as source:
    reader = csv.DictReader(source)
    rows = list(reader)
    assert reader.fieldnames == ["id", "active", "amount", "address", "note", "tags"]
assert len(rows) == 2
assert rows[0]["id"] == "00123"
assert rows[0]["active"] == "true" and rows[1]["active"] == "false"
assert rows[0]["amount"] == "1.10"
assert json.loads(rows[0]["address"]) == {"city": "Austin"}
assert json.loads(rows[1]["tags"]) == ["new", "trial"]
assert rows[0]["note"] == "Austin, TX"
assert rows[1]["amount"] == rows[1]["address"] == rows[1]["note"] == ""
print("Example checks passed; source distinctions are still lost as documented.")

Run it with py -3 -I .\check_output.py on Windows or python3 -I check_output.py on macOS/Linux. For your own file, replace these example assertions with checks of its actual required IDs, columns, decimals and nested values. Keep the original source and a small input/output comparison with the conversion report.

Decide when to flatten or expand nested data

Storing nested JSON in a cell preserves its structure for software that explicitly parses that cell. It does not make the nested fields available as ordinary spreadsheet columns.

If the destination needs a city column, name its exact source path and output name, such as address.city to city. Decide what happens when the path is absent, null or not an object. Check collisions if the source already contains a city column or dotted key. Do not blindly merge both into the same header.

For an array of order lines, choose one row per order or one row per line. Expanding changes the row count and repeats order-level values, which can double-count totals in later analysis. Document the row grain before writing a different converter. This helper deliberately does not flatten or explode.

Protect the handoff to spreadsheets and other applications

CSV does not enforce column types. Import ID and ZIP-code columns as text in the receiving application; double-clicking the file may let that application reinterpret 00123 as a number. Confirm delimiter, encoding and type settings on a small sample before importing the full file.

The helper blocks several common formula-like string prefixes rather than changing data silently. This is not a universal spreadsheet-safety test. If such content is intentional, stop and choose a reviewed export policy for the actual destination. Do not disable the check merely to make the run finish.

Fix common conversion failures

ProblemLikely reasonAction
Expected array-of-objects errorA single object or wrapper was suppliedInspect the shape and explicitly select the intended record list
Duplicate-key errorThe source repeats a property nameResolve the source ambiguity rather than silently keeping the last value
Nested JSON appears in one cellThis is the chosen policyParse it downstream or define a flattening map for a different export
Empty cells are ambiguousNull, absent and empty use the same representationPreserve JSON or agree on a distinguishable schema before conversion
Output file existsThe script prevents replacementInspect it or choose a new output name
Spreadsheet changes IDs or decimalsImport inferred a typeReimport with explicit column types and compare the original

Continue with a reusable workflow

For repeated jobs, review json-records-to-csv and its actual nested-field policy before substituting it for this example. csv-to-json-records can support a reverse workflow, but cannot recover distinctions already lost in CSV. If the records are a URL inventory, continue to create a sitemap XML.

Frequently asked questions

Can JSON be converted to CSV without losing information?

Only under an explicit representation that preserves everything your task requires. Ordinary blank cells cannot distinguish a missing key, null and an empty string. Keep the source or use a documented typed encoding when that distinction matters.

Does this flatten nested JSON?

No. It serializes nested objects and arrays as JSON inside a cell. Flattening needs a mapping and collision policy; expanding arrays also needs a row-grain decision.

Do I need an AI service for the conversion?

No. The script runs locally. An agent can help select a mapping or explain failures, but this example does not require uploading the file or paying for a service.

Platform Score is our assessment under a published method. It is not a safety guarantee.

Next steps

  1. Create a Sitemap XML: Generate, Validate and Submit Read next.
  2. Convert XML to JSON: Attributes, Repeats and Namespaces Read next.
  3. All guides by topic Browse everything.

Sources

This page is not offered to search engines yet: The content file does not mark this page indexable yet.