How can I read and write a JSON Lines file one record per line?
Quick answer
Treat a JSON Lines file as one complete JSON value per physical line, not as one JSON array. In Python, iterate over the file and call json.loads() on each nonblank line; catch json.JSONDecodeError and include the line number in the error. To write records, call json.dumps() once per value and add a newline. This assumes each record fits on one line; JSON Lines implementations may differ in their requirements. [S1]
The question, the details, the next step.
A practical checklist
Confirm the input uses one complete JSON value per physical line.
Choose and document how blank lines should be handled.
Track physical line numbers and report parse errors with useful details.
Write each serialized value followed by a newline.
Use a separate destination when you need to preserve the original file.
Check application-specific fields and types separately from JSON parsing.
A few more useful answers
Why not load the whole JSON Lines file with `json.load()`?
json.load() reads a JSON document, whereas this approach treats each physical line as a separate value. Iterate over the lines and parse them individually. [S1]
Does the example keep valid records when another line is malformed?
Yes. Its continue skips the malformed line and proceeds, while printing that line’s number and parse message. Remove that behavior or change it if your task should stop on an error.
Does a successful parse mean the record has the fields my program needs?
No. Parsing checks whether the line is valid JSON; it does not check application-specific requirements such as required keys or expected value types.
Sources
References used for this guide.
- [S1] Python json module: document framing and decode errors docs.python.org · Checked
