Recent chats
ASKGEEZ Q&A GUIDETechnology & devices

How can I convert a small JSON array of objects to CSV?

Quick answer

In Python, load the JSON and confirm it is a list of objects. Choose an explicit CSV column order, then compare each object’s keys with that field list before writing. Decide how to handle missing fields and extra keys: for example, write missing values as blank, but report and skip records with extra keys. Write the CSV to a separate path so the JSON input remains untouched. [S1] [S2]

LET’S WORK THROUGH IT

The question, the details, the next step.

Question

What should I decide before converting a small JSON array to CSV?

Geez

Decide the CSV schema first: the exact columns, their order, and what to do when an object does not match. Python’s JSON decoder represents an array as a list and objects as dictionaries, so you can check the structure before writing. [S2]

For example, suppose the input is:

[
  {"name": "Mina", "team": "Design", "city": "Riga"},
  {"name": "Omar", "team": "Support"},
  {"name": "Lee", "team": "Sales", "city": "Oslo", "level": 2}
]

You might choose name, team, city as the fields, in that order. Decide whether a missing city becomes a blank cell and whether an unlisted key such as level makes the record incompatible. Reporting the extra key and skipping that record is one clear policy; adding level to the schema is another. Choose deliberately so data is not lost without notice.

Follow-up question

How do I check the records and write the CSV without silently dropping anything?

Geez

This example writes to a different file, accepts missing listed fields as blank, and reports records with extra fields instead of writing them. Replace the path placeholders. DictWriter uses the explicit fieldnames order for columns; its default behavior raises on extra keys, so the code checks them first. [S1]

import csv
import json
from pathlib import Path

json_path = Path("[input.json]")
csv_path = Path("[output.csv]")
fields = ["name", "team", "city"]

with json_path.open(encoding="utf-8") as source:
    records = json.load(source)

if not isinstance(records, list):
    raise ValueError("Expected the top-level JSON value to be an array")

issues = []
compatible = []

for index, record in enumerate(records):
    if not isinstance(record, dict):
        issues.append(f"Record {index}: expected an object; skipped")
        continue

    missing = [field for field in fields if field not in record]
    extra = [key for key in record if key not in fields]

    if extra:
        issues.append(f"Record {index}: extra keys {extra}; skipped")
        continue

    if missing:
        issues.append(
            f"Record {index}: missing keys {missing}; blank cells written"
        )
    compatible.append(record)

with csv_path.open("w", encoding="utf-8", newline="") as output:
    writer = csv.DictWriter(output, fieldnames=fields, restval="")
    writer.writeheader()
    writer.writerows(compatible)

print(f"Wrote {len(compatible)} records to {csv_path}")
print("Issues:")
for issue in issues:
    print(f"- {issue}")

With the sample, the second record is written with a blank city; the third is skipped and reported because of level. Indexes start at zero, so Record 1 means the second item. The code checks input shape and keys, not whether values suit your project.

Follow-up question

What output and issue report should I expect for that example?

Geez

The CSV would contain a header and the first two records:

name,team,city
Mina,Design,Riga
Omar,Support,

The report would include Record 1: missing keys ['city']; blank cells written and Record 2: extra keys ['level']; skipped. The CSV column order follows the explicit fields list. [S1]

If you need to retain level, add it intentionally to fields and decide how to handle records where it is missing. Review the report before relying on the CSV.

Follow-up question

What should I check before using the converted file?

Geez

Check that the CSV has the intended header and order, that the number of written records is expected, and that each reported issue has an intentional resolution. If you revise the field list, rerun the conversion and review the new report.

This example checks that the top-level value is a list, each item is an object, and keys are missing or extra. It does not validate value types or whether the columns meet a particular system’s requirements; define those rules for your intended use.

A practical checklist

  • Set separate input JSON and output CSV paths.

  • Confirm the parsed top-level value is a list and its items are objects.

  • Choose the exact CSV fields and their order.

  • Decide how to handle missing fields and extra keys.

  • Review the issue report, CSV header, and written-record count.

A few more useful answers

Can I include every key that appears anywhere in the array?

Yes. You can build a field list from keys across the objects, but choose its order explicitly and review the resulting schema. The example uses a fixed field list so unexpected keys are reported.

Does a missing field have to make the whole record invalid?

No. The example reports a missing listed field and writes a blank cell. Python’s DictWriter supports a restval value for missing keys; choose a value and policy that fit your data. [S1]

What happens if I set `extrasaction` to `ignore`?

Python’s DictWriter can ignore unlisted keys with that setting, but those values would be discarded. Compare keys and report extras first, or revise the field list deliberately, to avoid silent information loss. [S1]

Sources

References used for this guide.

  1. [S1] Python csv module: DictReader and DictWriter behavior
    docs.python.org · Checked
  2. [S2] Python json module: decoding JSON arrays and objects
    docs.python.org · Checked

YOUR QUESTION. YOUR DETAILS.

Let’s work through your situation.

Get a tailored answer or help with your next task. Starts at $1, with a quote before you pay.

Ask your own question
← Back to Geez at Work