Home / Blog / Transliteration & conversion

Spreadsheet formats & CSV

How To Convert JSON To CSV In Python Using Pandas?

Use pandas.json_normalize for a JSON list of records, choose the exported columns, and write them with DataFrame.to_csv.

How To Convert JSON To CSV In Python Using Pandas?

Use pandas.json_normalize for a JSON list of records, choose the exported columns, and write them with DataFrame.to_csv. Normalization can flatten nested objects, but list-valued fields still need a separate decision.

Set up the conversion

The example accepts records containing id, name and a nested address.city. json_normalize creates a dotted address.city column. Validate those required columns before selecting them so a missing or renamed source field stops the export. This example leaves one output row per input object; it does not explode arrays.

A reproducible conversion example

import json
import pandas as pd

with open("input.json", encoding="utf-8") as source:
    records = json.load(source)
if not isinstance(records, list) or any(not isinstance(x, dict) for x in records):
    raise ValueError("Expected a list of record objects")
df = pd.json_normalize(records, sep=".")
columns = ["id", "name", "address.city"]
if not set(columns).issubset(df.columns):
    raise ValueError("Missing an export column")
if any(df[c].map(lambda v: isinstance(v, (list, dict))).any() for c in columns):
    raise ValueError("Selected columns must contain scalar values")
df.loc[:, columns].to_csv("output.csv", index=False, encoding="utf-8")

The code is an illustrative conversion core. Run it in an isolated working folder with the named test files, install only the dependencies used by the example, and handle its reported errors before applying it to a larger dataset. It does not contact a remote conversion service.

Check the expected result

Test two records whose cities differ, one name with a comma, and a missing city. Decide whether missing values may become blank CSV cells or should cause an error. Check that exactly three named columns are exported and no numeric DataFrame index appears. If id is already a number in JSON, converting it to text later cannot recover leading zeros that the source never contained.

Format-specific limits

Flattened dotted names can collide with literal source keys containing dots. Inspect the normalized column set and choose a separator or mapping that avoids ambiguity. For order arrays, use a documented record_path and meta mapping, then test the expected increased row count. JSON Lines can be read in chunks with an appropriate read_json workflow; a giant JSON array needs a different streaming strategy.

Verify the file contract before using the result

Write down the delimiter, encoding, header names, field order and treatment of empty values. Keep the original file unchanged and write the converted output to a different path. Conversion is successful when a parser for the destination format recovers the intended values; a familiar filename extension or a successful save message is not enough.

Start with a small fixture that contains the cases your real data can contain. Include a leading-zero identifier, a quoted comma, an embedded quotation mark, a blank field and a non-ASCII character. Add a multiline field only if both formats and the receiving system support it. Verify the fixture first, then run a bounded sample from the real input. Record parsed row counts and check the first and last records so truncation or an accidental duplicate header is visible.

Keep identifiers separate from quantities. An account-like or product identifier may contain digits while still being text; converting it to a floating-point number can remove leading zeros or precision. Dates also need an agreed format. When a conversion produces an unexpected blank, investigate whether it came from an empty source cell, a missing field, an invalid value or an automatic missing-value rule. Those conditions can require different downstream handling.

Do not resolve malformed records by silently skipping them unless that behavior is an explicit requirement and the skipped records are reported. Use a failure message that identifies the record or field, retain enough context to correct the input, and avoid exposing sensitive contents in public logs. For production automation, write to a temporary destination and promote it only after validation so a failed run cannot replace a previously good export.

Where the browser tool fits

Convert Text to CSV helps with already extracted plain text. It does not replace a workbook reader, a JSON parser, an XML schema validator or a Parquet engine. Use it only when its input structure and delimiter choices match your actual data. For structured source files, perform the format-aware conversion above and check the result with an independent reader.

Primary reference

Official format and API documentation