Web scraping
How do I convert scraped JSON to CSV?
Flatten each record into a single level of keys, decide the column list once, and write the rows with Python's csv module or pandas.
The core idea
CSV is a flat table: every row has the same columns, and every cell holds one value. Scraped JSON is often nested, with objects inside objects and lists of variants or images. Converting means deciding how each nested piece becomes a column, or several columns, or several rows. Once that is decided, the writing itself is a few lines.
With the standard library
import csv, json
def flatten(obj, prefix=""):
flat = {}
for key, val in obj.items():
name = f"{prefix}{key}"
if isinstance(val, dict):
flat.update(flatten(val, name + "."))
elif isinstance(val, list):
flat[name] = "|".join(str(v) for v in val)
else:
flat[name] = val
return flat
records = [flatten(r) for r in json.load(open("listings.json", encoding="utf-8"))]
columns = sorted({k for r in records for k in r})
with open("listings.csv", "w", newline="", encoding="utf-8") as fh:
out = csv.DictWriter(fh, fieldnames=columns, extrasaction="ignore")
out.writeheader()
out.writerows(records)
Nested keys become dotted column names such as seller.name, lists are joined with a pipe, and the column set is the union of every record's keys so nothing is dropped. newline="" stops blank lines appearing between rows on Windows.
With pandas
For bigger or messier data, pandas.json_normalize does the flattening and can expand lists of objects into their own rows:
import pandas as pd
raw = pd.read_json("listings.json")
offers = pd.json_normalize(raw.to_dict("records"), record_path="offers",
meta=["id", "title", ["seller", "name"]], sep=".")
offers.to_csv("offers.csv", index=False)
Here each offer of each listing becomes a row, with the listing id, title and seller name repeated on every offer row. That shape is what spreadsheets and BI tools handle best.
Decisions to make up front
- Lists of scalars (tags, image URLs): join into one cell, or keep only the first, or spread into
image_1,image_2columns up to a fixed maximum. - Lists of objects (variants, offers): one row per item, repeating the parent fields.
- Column order: fix it in code. Sorted or explicit lists keep files comparable from run to run.
- Missing values: leave cells empty rather than writing
Noneornull.
Common problems
Excel can mangle UTF-8 files with accents unless you write a byte order mark: use encoding="utf-8-sig" if the audience opens files in Excel. Long numeric ids such as product codes may be shown in scientific notation; keep them as text. Commas and newlines inside values are handled by the csv module's quoting, so never build CSV lines by joining strings with commas yourself. Finally, prices should stay as strings or decimals, not floats, to avoid rounding noise.
Streaming large files
If your scraper writes one JSON object per line (JSON Lines), you can convert without loading everything into memory: read a line, flatten it, write a row. That requires the column list in advance, so define it explicitly instead of collecting keys from all records. For multi-gigabyte data, a columnar format such as Parquet is often a better destination than CSV.
When CSV is the wrong target
CSV loses types and structure. If the data feeds another program rather than a spreadsheet, store JSON Lines or load into a database instead, and export CSV only for the people who need it. The page on pipeline architecture discusses where each format fits, and nested JSON in JavaScript covers the same task in Node. For getting the JSON in the first place, see reading JSON from a response.
Common questions
Why are there blank lines between rows in my CSV?
Open the file with newline="" when using Python's csv module, especially on Windows.
How do I keep accents readable in Excel?
Write the file with utf-8-sig encoding so Excel detects UTF-8.
What do I do with lists inside records?
Join simple lists into one cell, or expand lists of objects into separate rows with json_normalize.
Can I convert without pandas?
Yes. The csv module plus a small flatten function handles most scraped data.
Why do my product ids show as 1.23E+12?
Spreadsheet software guesses numbers. Keep ids as text, or prefix them so they are not read as numbers.
Keep reading
- JSONThe text format of objects, arrays, strings, numbers, booleans and null that almost every web API speaks, with the mistakes to avoid.
- How do I read JSON from a response in Python?Call response.json() after checking status and content type, and pull JSON embedded in HTML with a parser.
- How do I handle nested JSON in JavaScript?Read deep fields with optional chaining and defaults, flatten arrays with flatMap, and walk unknown shapes with a small recursive helper.
- Data extractionData extraction turns raw HTML or JSON into clean, typed records with a fixed schema that downstream tools can trust.