In pandas, how do you load a newline-delimited JSON event log with nested user objects and item arrays into flat DataFrames?
answer
- one object per line
- nested values stay Python objects
- a separate flattening function
- record_path plus meta
- wrap text in a buffer
basics
~10 sRead it with pd.read_json(path, lines=True), which keeps nested objects as dicts and arrays as lists, then flatten with pd.json_normalize: nested keys become dotted columns, and record_path with meta gives one row per array element.
solid answer
~40 s`pd.read_json(path, lines=True)` reads one JSON object per line into one column per top-level key; nested objects stay as `dict`s and arrays as `list`s in object columns. `pd.json_normalize` flattens them: on a list of records it turns `{"user": {"id": ...}}` into a `user.id` column (`sep` changes the dot, `max_level` limits depth), and `record_path='items', meta=['event_id']` gives one row per item with the parent's `event_id` repeated. For big files, `chunksize` with `lines=True` returns an iterator. Two pandas 3.0 details: JSON text in a string must be wrapped in `io.StringIO`, and `json_normalize` on a Series now keeps that Series' index, so the result joins back to the original frame.
code
python · 21 linesimport json
from io import StringIO
import pandas as pd
text = (
'{"event_id": 1, "user": {"id": "u7", "plan": "pro"}, "items": [{"sku": "A", "qty": 2}]}\n'
'{"event_id": 2, "user": {"id": "u9", "plan": "free"}, '
'"items": [{"sku": "B", "qty": 1}, {"sku": "C", "qty": 5}]}\n'
)
events = pd.read_json(StringIO(text), lines=True)
print(events.columns.tolist()) # ['event_id', 'user', 'items']
users = pd.json_normalize(events["user"]) # keeps events' index in pandas 3.0
print(events[["event_id"]].join(users).columns.tolist()) # ['event_id', 'id', 'plan']
records = [json.loads(line) for line in text.splitlines()]
items = pd.json_normalize(records, record_path="items", meta=["event_id", ["user", "id"]])
print(items.columns.tolist()) # ['sku', 'qty', 'event_id', 'user.id']
print(len(items)) # 3go deeper
Recall that lines=True reads one JSON object per line and that json_normalize turns nested objects into columns.
Explain record_path and meta, the dotted column names and sep, and why nested values stay dicts after read_json.
Handle real logs: chunksize iteration, the dtype and date inference read_json applies, and the pandas 3.0 StringIO and Series-index changes.
Decide where flattening happens in a pipeline and which flat, typed format the normalised events are stored in for downstream jobs.
## Newline-delimited JSON with `read_json(lines=True)` Event logs are usually **JSON Lines**: one JSON object per line, no surrounding array. `pd.read_json(path_or_buf, *, orient=None, typ='frame', dtype=None, convert_dates=True, lines=False, chunksize=None, nrows=None, engine='ujson', ...)` reads them with **`lines=True`**; with the default `lines=False` it expects one JSON document and fails on a file of many. - **`chunksize`** returns a `JsonReader` that yields DataFrames of that many lines; it is only allowed with `lines=True`, and use it as a context manager. - **`nrows`** reads only the first lines; also `lines=True` only. - **`engine='pyarrow'`** is accepted only for line-delimited input and does not support `chunksize`. - **`compression='infer'`** reads `.gz` and similar files directly. Writing the same shape back is `df.to_json(path, orient='records', lines=True)`; `lines=True` with any other `orient` raises `ValueError`. Two writer details matter in practice: - In pandas 3.0, `to_json` on a frame with datetime columns and no `date_format` emits a `Pandas4Warning`, because the implicit `'epoch'` (milliseconds since 1970) format is deprecated; pass `date_format='iso'`. - Also in pandas 3.0, `Decimal` values are encoded as strings rather than floats. ## When the file is one JSON document Not every JSON file is JSON Lines. For a single document, `orient` tells `read_json` how the document is laid out: | `orient` | document shape | |---|---| | `'records'` | `[{column: value}, ...]`, a list of row objects | | `'columns'` (default for a DataFrame) | `{column: {index: value}}` | | `'index'` | `{index: {column: value}}` | | `'split'` | `{"index": [...], "columns": [...], "data": [...]}` | | `'values'` | a bare array of row arrays | | `'table'` | a Table Schema document with a `schema` and `data` part | `'table'` is the only orient that carries dtypes with the data, which is why it round-trips more faithfully than the others. An API response that wraps the rows inside a larger object (`{"meta": ..., "results": [...]}`) is usually easier to load with the standard `json` module and `json_normalize(doc["results"])` than with any `orient`. ## What `read_json` does with nested fields `read_json` builds one column per **top-level key**. A nested object stays a Python `dict` inside an object column, and a nested array stays a `list`. Nothing is flattened. That is where `pd.json_normalize` comes in. Watch type inference too. With the default `dtype`, columns whose strings all parse as numbers are converted (`"00123"` becomes `123`), and with `convert_dates=True` columns whose names look date-like (ending in `_at` or `_time`, starting with `timestamp`, or named `modified` or `date`, among others) are parsed as datetimes. Pass `dtype={"account": "str"}` or `convert_dates=False` when that guess is wrong. ## Flattening with `json_normalize` `pd.json_normalize(data, record_path=None, meta=None, meta_prefix=None, record_prefix=None, errors='raise', sep='.', max_level=None)` turns dicts (or a list of dicts, or a Series of dicts) into a flat table: | goal | call | result | |---|---|---| | nested objects to columns | `json_normalize(records)` | `user.id`, `user.plan` columns, one row per record | | one row per element of a nested list | `json_normalize(records, record_path="items", meta=["event_id"])` | one row per item, with `event_id` repeated | | keep a deep field from the parent | `meta=["event_id", ["user", "id"]]` | adds a `user.id` column | | stop flattening early | `max_level=1` | deeper dicts stay as dicts | | different separator | `sep="_"` | `user_id` instead of `user.id` | `errors='raise'` (default) raises `KeyError` when a `meta` key is missing from a record; `'ignore'` fills it with NaN. ## The pandas 3.0 changes that bite here 1. **Literal JSON text is no longer accepted.** In pandas 3.0, `read_json` (like `read_excel`, `read_html` and `read_xml`) treats a string argument as a path or URL; JSON text must be wrapped in `io.StringIO` (bytes in `io.BytesIO`). Passing the text directly was deprecated in 2.1 and now fails, typically with `FileNotFoundError`. 2. **`json_normalize` on a Series keeps the Series index.** In pandas 3.0, `pd.json_normalize(events["user"])` returns rows labelled with `events`' index; in 2.x the result got a fresh `RangeIndex`. After filtering `events`, the 3.0 behaviour is what makes `events.join(pd.json_normalize(events["user"]))` line up. ## A typical flow ```python from io import StringIO import pandas as pd events = pd.read_json(StringIO(text), lines=True) users = pd.json_normalize(events["user"]) # same index as events in 3.0 flat = events.drop(columns=["user"]).join(users.add_prefix("user.")) ``` ## Mistakes to avoid - Calling `read_json` without `lines=True` on a JSON Lines file. - Expecting `read_json` to flatten nested objects into columns. - Passing `chunksize` without `lines=True`, which raises `ValueError`. - Losing leading zeros or getting surprise datetimes from the default inference. - Exploding arrays by hand with loops when `record_path` and `meta` already do it.
- The log is 40 GB. How do you process it without loading it all?Use `pd.read_json(path, lines=True, chunksize=100_000)` as a context manager; it yields DataFrames of that many lines, and you normalise and aggregate each chunk before moving on. `chunksize` requires `lines=True` and is not supported with `engine='pyarrow'`.
- An account_code field like "00123" comes back as 123. Why, and how do you stop it?With the default `dtype`, `read_json` tries to convert string columns to numbers and keeps the conversion when every value parses, so the zeros go. Pass `dtype={"account_code": "str"}` to keep the text.
- Expects read_json to flatten nested objects into separate columns
- Reads a JSON Lines file without lines=True
- Passes the JSON text itself as a string to read_json in pandas 3.0
- Uses chunksize on read_json without lines=True
- Loops over rows to explode item arrays instead of using record_path and meta
Assumes pandas 3.0: literal JSON strings to read_json were deprecated in 2.1 and are rejected in 3.0 (wrap in StringIO); json_normalize on a Series keeps its index in 3.0, where 2.x returned a new RangeIndex; to_json warns on the implicit epoch date format in 3.0.