Updated November 24, 2026 | Developer Guides | Applied JSON tutorials

A standard JSON file contains one complete JSON value. JSON Lines, often called NDJSON in related contexts, uses a different convention: one independent JSON value on each line. The approach is useful for append-friendly logs, event feeds and large datasets where processing records one at a time is preferable to loading a giant array.

What you will learn: This focused guide covers json lines ndjson with working-style examples, common problems and the next checks needed before relying on the result. Use synthetic inputs when practising online.

JSON arrays versus newline-delimited records

A normal JSON array encloses elements in square brackets and separates them with commas. JSON Lines writes a valid JSON value on each non-empty line, normally using UTF-8 and newline separators. The full multi-line file is not one standard JSON document, even though each individual line is valid JSON.

{"event":"login","user":"u1"}
{"event":"purchase","user":"u2","total":14.5}
{"event":"logout","user":"u1"}

Because each line is self-contained, a process can consume one record at a time or append a new event without rewriting a closing array bracket. Verify the exact JSON Lines or NDJSON conventions expected by the receiving system.

Read JSON Lines with Python

Read a file sequentially and parse each non-empty line using json.loads. This can use less memory than collecting an entire multi-gigabyte JSON array in one Python object. Include line numbers so malformed records can be located and handled according to your import policy.

import json
with open("events.jsonl",encoding="utf-8") as f:
    for number,line in enumerate(f,start=1):
        if not line.strip():
            continue
        try:
            event=json.loads(line)
        except json.JSONDecodeError:
            print(f"Invalid event on line {number}")
            continue
        print(event.get("event"))

The example expects objects; general JSON Lines can also contain other JSON values. Validate the type before calling dict-only methods in production.

Write one record per line

To produce JSON Lines, serialize each object separately, append a newline and avoid adding commas between records. The widely used .jsonl extension signals the convention but does not itself guarantee a file’s content is well formed.

import json
records=[{"id":1,"ok":True},{"id":2,"ok":False}]
with open("events.jsonl","w",encoding="utf-8") as f:
    for item in records:
        f.write(json.dumps(item,ensure_ascii=False)+"\n")

For continuous logging, plan buffering, file rotation and backpressure so that disks and consumers do not become bottlenecks.

When NDJSON is useful

Event streams, model training datasets, telemetry and large ETL jobs frequently need independent records. A line-oriented format can be simpler to process incrementally than a single enormous array. However, line-by-line processing cannot easily express a shared top-level schema unless consumers enforce an external contract.For compact data exchange in a small web API, a normal JSON object or array may be easier. Format selection should follow the transport and processing pattern.

Common pitfalls and validation

Do not paste an entire JSON Lines document into a validator expecting one JSON root; it will usually report extra content after the first record. Validate each line separately, or use a dedicated NDJSON parser. Also avoid embedding literal unescaped newline characters inside string values, since those break line boundaries; JSON’s escaped n is safe within strings.When working internationally, use UTF-8 consistently and test records containing Chinese names or accented locations. Maintain field-level contracts even though each line parses independently.

Frequently asked questions

Is NDJSON the same as standard JSON? Each line contains JSON, but the whole file generally is not one JSON document. What extension should I use? .jsonl and .ndjson are common conventions. Can I open it with a JSON formatter? Usually one line at a time unless the tool supports JSON Lines. Can each line contain an array? The convention typically expects one valid JSON value per line, so arrays can be used where the receiving system allows. Does NDJSON compress well? It often can, but evaluate real workloads.

Quick implementation and quality checklist

  • Confirm that the input is valid JSON or an expected source format before transforming it.
  • Check the expected field types, nested structure, empty values and error cases.
  • Use correct UTF-8 handling for multilingual content and protect user or client privacy.
  • Define currency and time-zone rules explicitly for distributed projects serving the USA, UK, Canada, Australia and China.
  • Verify a small representative output against the receiving application’s contract.

These checks support reuse across markets without assuming that every commercial tool or hosted service is available worldwide.

Try related free tools on Perkability Rewards

The links below open existing tools directly, not a new landing page. For context, also see our previously published JSON error fixes and nested JSON arrays articles.

  • JSON Formatter: practise with test examples related to this subject.
  • Word Counter: practise with test examples related to this subject.

Technical sources and further reading:

Advertising disclosure: This tutorial includes a clearly labeled 160×600 advertising banner and a social-bar script. The scripts are managed by a third-party advertising network; actual delivery varies by browser and platform settings. No claim of search-ranking or traffic results is made.

One Response

Leave a Reply

Your email address will not be published. Required fields are marked *