Skip to main content

Learn NDJSON in 5 Minutes

A fast-paced quick start guide to get you up and running with NDJSON format. Perfect for developers who learn by doing.

5 min read Quick Start Hands-On
A five-minute hourglass whose sand falls as tiny glowing NDJSON records

Quick Start Guide

Minute 1: What is NDJSON?

Diagram of the five-minute path in five steps: see the format, write a file, read it line by line, append filter and count, learn the habits
One step per minute. Each section below covers one of them.

Regular JSON

[
  {
    "id": 1,
    "name": "Alice",
    "email": "[email protected]"
  },
  {
    "id": 2,
    "name": "Bob",
    "email": "[email protected]"
  }
]

Entire file must be valid JSON

Cannot append without re-parsing

Entire file loaded into memory

NDJSON Format

{"id": 1, "name": "Alice", "email": "[email protected]"}
{"id": 2, "name": "Bob", "email": "[email protected]"}

One valid JSON object per line

Append-friendly (just add a new line)

Stream line-by-line (minimal memory)

The Key Concept

NDJSON is simply regular JSON objects, separated by newlines. Each line is a complete, self-contained JSON object. That's it!

Minute 2: Write Your First NDJSON File

Python

import json

# Sample data
users = [
    {"id": 1, "name": "Alice", "role": "developer"},
    {"id": 2, "name": "Bob", "role": "designer"},
    {"id": 3, "name": "Charlie", "role": "manager"}
]

# Write to NDJSON file
with open('users.jsonl', 'w') as f:
    for user in users:
        f.write(json.dumps(user) + '\n')

print("Created users.jsonl successfully!")

JavaScript (Node.js)

const fs = require('fs');

// Sample data
const users = [
    {id: 1, name: "Alice", role: "developer"},
    {id: 2, name: "Bob", role: "designer"},
    {id: 3, name: "Charlie", role: "manager"}
];

// Write to NDJSON file
// Note the trailing newline on every line, including the last one
const lines = users.map(user => JSON.stringify(user) + '\n').join('');
fs.writeFileSync('users.jsonl', lines);

console.log('Created users.jsonl successfully!');

Bash (Manual Creation)

# Create NDJSON file manually
cat > users.jsonl << 'EOF'
{"id": 1, "name": "Alice", "role": "developer"}
{"id": 2, "name": "Bob", "role": "designer"}
{"id": 3, "name": "Charlie", "role": "manager"}
EOF

echo "Created users.jsonl successfully!"

Minute 3: Read NDJSON Data

Python - Stream Processing

import json

# Read NDJSON file line by line (memory efficient!)
with open('users.jsonl', 'r') as f:
    for line in f:
        user = json.loads(line)
        print(f"{user['name']} is a {user['role']}")

# Output:
# Alice is a developer
# Bob is a designer
# Charlie is a manager

JavaScript - Async Stream

const fs = require('fs');
const readline = require('readline');

// Read NDJSON file with streams (memory efficient!)
// for await has to sit inside an async function - mixing require() with a
// top-level await is what makes Node refuse the file outright.
async function main() {
    const fileStream = fs.createReadStream('users.jsonl');
    const rl = readline.createInterface({
        input: fileStream,
        crlfDelay: Infinity
    });

    for await (const line of rl) {
        const user = JSON.parse(line);
        console.log(`${user.name} is a ${user.role}`);
    }
}

main();

Bash with jq

# Read and process with jq
cat users.jsonl | jq -r '"\(.name) is a \(.role)"'

# Filter developers only
cat users.jsonl | jq 'select(.role == "developer")'

# Count total lines
wc -l users.jsonl

Minute 4: Common Operations

Append New Data

Adding new records is simple - just append a new line!

# Python
with open('users.jsonl', 'a') as f:
    new_user = {"id": 4, "name": "Diana"}
    f.write(json.dumps(new_user) + '\n')

# Bash
echo '{"id": 4, "name": "Diana"}' >> users.jsonl

Filter Data

Process only the records you need

# Python
with open('users.jsonl', 'r') as f:
    for line in f:
        user = json.loads(line)
        if user['role'] == 'developer':
            print(user)

Convert to CSV

Transform NDJSON to other formats

# Bash with jq
cat users.jsonl | jq -r '[.id, .name, .role] | @csv'

# Output:
# 1,"Alice","developer"
# 2,"Bob","designer"

Count Records

Quick statistics without loading entire file

# Bash - count lines
wc -l users.jsonl

# Python - count while processing
count = sum(1 for line in open('users.jsonl'))
print(f"Total records: {count}")

Minute 5: Best Practices & Tips

Do

  • Use UTF-8 encoding for all files
  • One valid JSON object per line (no arrays)
  • Use \n (LF) for line endings
  • Stream process for large files (line-by-line)
  • Compress with gzip for storage (.jsonl.gz)
  • Use .jsonl extension (or .json / .ndjson)

Don't

  • Don't put arrays or objects across multiple lines
  • Don't use trailing commas after objects
  • Don't load entire file if you can stream
  • Don't mix JSON and NDJSON in same file
  • Don't forget error handling for malformed lines
  • Don't use NDJSON for deeply nested hierarchical data

When to Use NDJSON

AI/ML Training Data - OpenAI, Vertex AI, etc.
Application Logs - Structured logging
Data Streaming - Real-time pipelines
Big Data - Spark, Hadoop, ETL
Analytics Events - User tracking
API Responses - Streaming results

Tools iconNDJSON Cheat Sheet

Ten everyday jobs, one line each. Everything here works on a file of any size, because none of it loads the whole file.

You want toRun this
Count the recordswc -l data.jsonl
Look at the first five recordshead -n 5 data.jsonl
Pretty-print one recordhead -n 1 data.jsonl | jq .
Keep only matching recordsjq -c 'select(.status == "error")' data.jsonl
Pull out one fieldjq -r '.email' data.jsonl
Turn a JSON array into NDJSONjq -c '.[]' data.json > data.jsonl
Turn NDJSON into a JSON arrayjq -s '.' data.jsonl > data.json
Check that every line parsesjq -c . data.jsonl > /dev/null (stops with an error at the first bad line)
Add one recordecho '{"id": 4, "name": "Dana"}' >> data.jsonl
Compress it, then peek without unpackinggzip data.jsonl, then zcat data.jsonl.gz | head -n 3

Validate iconFive Mistakes Everyone Makes Once

Almost every broken NDJSON file fails for one of these reasons. Each takes seconds to spot once you know it. The common mistakes guide has the fixes in detail, and the validator names the exact line.

Diagram of five common first mistakes: a pretty-printed record, an array wrapper left on, a raw line break in a string, a printed object instead of JSON, and a byte order mark
Five ways a first file breaks. The table below has the fix for each.
MistakeWhat it looks likeFix
Pretty-printing a recordOne record spread over several indented linesWrite each record compact, on one line: json.dumps(obj), JSON.stringify(obj), jq -c
Keeping the array wrapperA [ on the first line, commas at the line ends, a ] on the lastRemove the brackets and commas. The newline is the only separator
A raw line break inside a stringA record that stops halfway and continues on the next lineLet a JSON library write the string. It turns the line break into \n
Printing a language object instead of JSONSingle quotes, True, NoneUse json.dumps(obj), never str(obj) or print(obj)
A byte order mark at the startThe first line fails and every other line is fineSave as UTF-8 without BOM

Specification iconQuestions Beginners Ask

Do I need a special library?

No. Every language with a JSON parser can read NDJSON: read a line, parse it, repeat. Libraries only add convenience such as type checks and compressed files.

Can each line have different fields?

Yes. Nothing in the format forces lines to match. Tools that load the file into a table are much happier when they do, so keep the keys consistent unless you have a reason not to.

Can a line be something other than an object?

Yes. Any JSON value is allowed: an array, a string, a number. In practice nearly every file uses one object per line, and most tools expect that.

Are blank lines allowed?

Avoid them. Some parsers skip an empty line and others reject the file. End the file with a single newline after the last record and write nothing between records.

How big can an NDJSON file get?

As big as your disk. Because a reader holds only one line at a time, a 50 GB file needs no more memory than a 50 KB one. Watch the size of a single line instead: one giant record defeats the point.

How do I edit one record?

Open small files in a text editor and change the line. For large files, stream the file through a script, rewrite the record you care about and write everything to a new file.

Next Steps

Quick Reference Card

File Extensions

.jsonl, .json, .ndjson

MIME Type

application/x-ndjson

De facto, not registered with IANA - see the definition

Line Ending

\n (LF - Unix style)

Encoding

UTF-8

Valid NDJSON Example

{"timestamp": "2026-01-15T10:00:00Z", "event": "login", "user_id": 123}
{"timestamp": "2026-01-15T10:01:15Z", "event": "page_view", "user_id": 123}
{"timestamp": "2026-01-15T10:02:30Z", "event": "purchase", "user_id": 456}