Convert a JSON Array of Objects to CSV with Column Selection

You pull data from an API, get back a JSON array of objects, and you need it as a CSV for a spreadsheet or a quick import into another system. The obvious path is to open a Python REPL and type out a loop. Or install a package you've never heard of that pulls in six dependencies. Neither of those is wrong, but both are more friction than the problem deserves. A 50-line script with zero external imports gets the job done in one invocation and stays readable when you need to tweak it six months later.

This script reads a JSON array of objects, writes CSV to stdout, and lets you pick which columns you want. It handles missing keys without crashing. No dependencies beyond the standard library. You can pipe it into anything else in your shell pipeline, redirect it to a file, or feed it from curl without an intermediate temp file.

Verified terminal output of json2csv.py — real test runs in a clean, network-isolated container.

Why column selection matters

Most "JSON to CSV" tools dump every key they encounter. If your API returns 40 fields per object and you only need three, you get a 40-column CSV with 37 of them empty or irrelevant. Spreadsheets choke on that. Import scripts that expect a fixed column order break. The --cols flag here lets you specify exactly which keys to extract, in the order you want them in the header row. If you don't pass it, the script walks the array and collects keys in first-appearance order, which is usually what you want for a quick-and-dirty export where you just need "everything that's there."

Where the JSON comes from

The input is rarely hand-written. It's the response body of a GET /orders call saved to disk, an export from a database tool, or the output of another command in a pipeline that happens to speak JSON. The shape is almost always the same: a top-level array where each element is an object with flat string and number fields. That's the shape this script targets, and it's the shape most "convert my API response" questions are actually asking about.

CSV stays the destination because every consumer already accepts it. Excel opens it without plugins, pandas.read_csv needs no adapter, SQL loaders have a clause that expects it, and because it's plain text you can diff two exports to see exactly what changed between runs.

How the script works

The argument parser sets up three inputs: the file path (or - for stdin), an optional comma-separated column list, and an optional substitute string for missing values. The default for missing values is an empty string, which is what most CSV consumers expect when a field simply wasn't present in the source object. You can override it with --missing N/A or whatever placeholder your downstream tool prefers.

Reading the input is straightforward. If the path is -, it reads from sys.stdin. Otherwise it opens the file. Both paths go through a try/except that catches OSError and prints a clear error to stderr before exiting with code 1. You'll never get a bare traceback for a typo'd filename, and the error message tells you exactly which file failed so you can fix the path and re-run.

The JSON parsing step catches json.JSONDecodeError separately so the error message tells you the file was read successfully but wasn't valid JSON, rather than conflating I/O failure with syntax failure. After parsing, there's an explicit type check: the top-level value must be a list. If someone hands it a bare object or an array of strings, the script exits with a message instead of producing a single-row CSV full of nonsense.

Column detection when --cols is not provided uses a set to track which keys have been seen and a list to preserve order. It iterates through every object in the array and appends each new key to the list exactly once. This means if row 0 has keys a, b and row 1 has keys b, c, your header will be a, b, c. First appearance wins on ordering, which matches how most people think about "the columns in this dataset."

The CSV writer is configured with lineterminator="\n" explicitly. On some systems the default is \r\n, which breaks downstream tools that expect Unix line endings. Writing to sys.stdout means you can redirect or pipe the output without touching a temp file, and the script never writes to disk unless you tell it to via shell redirection.

For each row, the script checks that the element is actually a dict. If it's a string or a number sitting in the array, it prints a warning to stderr with the row index and skips it. The row data is built with obj.get(c, a.missing) for each column, so a missing key produces your chosen substitute rather than raising a KeyError that kills the whole run halfway through.

Why warnings go to stderr

The split between stdout and stderr is deliberate. When you run python3 json2csv.py data.json > out.csv, everything the script prints to stdout lands in out.csv — including any warning text, which would corrupt your CSV. Skipped-row warnings and error messages therefore go to stderr: they stay on your terminal where you can read them, and the file contains only the header row and data rows. The exit code closes the loop: 0 means the output is complete and clean, 1 means it isn't, so a shell script or cron job can branch on it.

Verification

I ran this in a clean Ubuntu container. Five test cases, all passing:

  • Column selection: python3 /work/json2csv.py /tmp/testdata/normal.json --cols name,age produced:
name,age
alice,30
bob,25
carol,40
  • Missing key substitution: python3 /work/json2csv.py /tmp/testdata/missing.json --cols id,name,tag --missing N/A produced:
id,name,tag
1,x,a
2,N/A,b
3,z,N/A
  • Edge cases (non-object rows in the array, missing keys with default empty string): python3 /work/json2csv.py /tmp/testdata/edge.json produced:
a,b
1,2
3,
5,6
  • Non-array top-level JSON: exited non-zero with an error message.
  • Nonexistent file path: exited non-zero with an error message.

Five passed, zero failed. No fixes were needed; the logic was correct on the first pass through the container. The edge-case test confirmed that a non-dict element in the array triggers the stderr warning and gets skipped without aborting the remaining rows.

What the container boundary buys you

The runs above happened in a clean Ubuntu container with no network access. The harness created its fixture files under /tmp/testdata before each run and invoked the script at /work, capturing everything it printed into the transcript quoted here. Nothing on that machine could influence the result — no leftover state from a previous run, no access to host files — so if the output is correct in the container, it's correct anywhere Python 3 runs.

The script

#!/usr/bin/env python3
"""Convert JSON array of objects to CSV with column selection and missing-value handling."""
import argparse, csv, json, sys

def main():
    p = argparse.ArgumentParser(description="JSON array → CSV")
    p.add_argument("input", help="Path to JSON file (or - for stdin)")
    p.add_argument("--cols", help="Comma-separated columns (default: all keys, first-appearance order)")
    p.add_argument("--missing", default="", help="Substitute for missing keys (default: empty string)")
    a = p.parse_args()

    try:
        raw = sys.stdin.read() if a.input == "-" else open(a.input).read()
    except OSError as e:
        print(f"error: cannot read input: {e}", file=sys.stderr); sys.exit(1)

    try:
        data = json.loads(raw)
    except json.JSONDecodeError as e:
        print(f"error: invalid JSON: {e}", file=sys.stderr); sys.exit(1)

    if not isinstance(data, list):
        print("error: top-level must be a JSON array", file=sys.stderr); sys.exit(1)

    cols = a.cols.split(",") if a.cols else None
    if cols is None:
        seen, cols = set(), []
        for obj in data:
            if isinstance(obj, dict):
                for k in obj:
                    if k not in seen:
                        seen.add(k); cols.append(k)

    w = csv.writer(sys.stdout, lineterminator="\n")
    w.writerow(cols)
    for i, obj in enumerate(data):
        if not isinstance(obj, dict):
            print(f"warning: row {i} not an object, skipping", file=sys.stderr); continue
        w.writerow([obj.get(c, a.missing) for c in cols])

if __name__ == "__main__":
    main()

How to use it

Basic conversion, all columns, output to a file:

python3 json2csv.py /path/to/data.json > output.csv

Select specific columns and set a missing-value placeholder:

python3 json2csv.py /path/to/data.json --cols id,name,email --missing N/A > subset.csv

Pipe from another command, like curl or jq:

curl -s https://api.example.com/users | python3 json2csv.py - --cols username,role

The script exits 0 on success and 1 on any error. Warnings about skipped non-object rows go to stderr, so they won't pollute your CSV output when you're redirecting stdout to a file.

Piping straight from an API

If the endpoint wraps the array in an object — the common {"results": [...]} shape — trim it first with jq .results before the pipe, so the script receives the bare array it expects. The - argument is what tells it to read stdin instead of a path, and everything else — column selection, missing-value substitution, exit codes — behaves exactly as it does with a file.


Luke Keam
Spot a bug or want a custom utility built? I'd love to hear from you. Get in touch
Luke Keam | techgeek.biz