Getting Started with NDJSON
A complete beginner-friendly tutorial to master Newline Delimited JSON format in 10 minutes. From your first NDJSON file to production-ready code.

Tutorial Contents
Short on time? Learn NDJSON in 5 minutes condenses this tutorial into a single hands-on page.
What is NDJSON?
Regular JSON
[
{"name": "Alice", "age": 30},
{"name": "Bob", "age": 25},
{"name": "Charlie", "age": 35}
]One big array - must load everything into memory
NDJSON Format
{"name": "Alice", "age": 30}
{"name": "Bob", "age": 25}
{"name": "Charlie", "age": 35}One JSON object per line - stream line by line
Key Concept: NDJSON is simply JSON objects separated by newlines. Each line is a complete, valid JSON object. That's it!
Your First NDJSON File
Step 1: Create a new file
Create a file named users.jsonl (or users.json - both extensions work!)
Step 2: Add your data
Type or paste this content:
{"id": 1, "name": "Alice Johnson", "email": "[email protected]", "role": "developer"}
{"id": 2, "name": "Bob Smith", "email": "[email protected]", "role": "designer"}
{"id": 3, "name": "Charlie Brown", "email": "[email protected]", "role": "manager"}Congratulations!
You just created your first NDJSON file! Each line is a complete JSON object representing one user.
Reading NDJSON Files

Python
Method 1: Standard Library (Recommended)
import json
# Read line by line - memory efficient!
with open('users.jsonl', 'r') as file:
for line in file:
user = json.loads(line)
print(f"Name: {user['name']}, Role: {user['role']}")
# Output:
# Name: Alice Johnson, Role: developer
# Name: Bob Smith, Role: designer
# Name: Charlie Brown, Role: managerMethod 2: Load All Data
import json
# Read all at once (use only for small files)
users = []
with open('users.jsonl', 'r') as file:
for line in file:
users.append(json.loads(line))
print(f"Total users: {len(users)}") # Total users: 3JavaScript (Node.js)
Using readline module
const fs = require('fs');
const readline = require('readline');
async function readJSONL(filename) {
const fileStream = fs.createReadStream(filename);
const rl = readline.createInterface({
input: fileStream,
crlfDelay: Infinity
});
for await (const line of rl) {
const user = JSON.parse(line);
console.log(`Name: ${user.name}, Role: ${user.role}`);
}
}
readJSONL('users.jsonl');Go
Using bufio.Scanner
package main
import (
"bufio"
"encoding/json"
"fmt"
"os"
)
type User struct {
ID int `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
Role string `json:"role"`
}
func main() {
file, _ := os.Open("users.jsonl")
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
var user User
json.Unmarshal(scanner.Bytes(), &user)
fmt.Printf("Name: %s, Role: %s\n", user.Name, user.Role)
}
}Kept short to show the shape. Two things to add before this reads real data: bufio.Scanner refuses any line longer than 64KB and then stops quietly, so call scanner.Buffer to raise the limit and check scanner.Err() after the loop. The examples page shows the hardened version.
Writing NDJSON Files
Python
import json
users = [
{"id": 1, "name": "Alice Johnson", "role": "developer"},
{"id": 2, "name": "Bob Smith", "role": "designer"},
{"id": 3, "name": "Charlie Brown", "role": "manager"}
]
# Write to NDJSON file
with open('output.jsonl', 'w') as file:
for user in users:
# Write each object as JSON on its own line
file.write(json.dumps(user) + '\n')
print("File written successfully!")Important!
Always add \n after each JSON object. Don't forget the newline!
JavaScript (Node.js)
const fs = require('fs');
const users = [
{id: 1, name: "Alice Johnson", role: "developer"},
{id: 2, name: "Bob Smith", role: "designer"},
{id: 3, name: "Charlie Brown", role: "manager"}
];
// Create write stream
const writeStream = fs.createWriteStream('output.jsonl');
// Write each object
users.forEach(user => {
writeStream.write(JSON.stringify(user) + '\n');
});
writeStream.end();
console.log('File written successfully!');Common Mistakes to Avoid
Missing Newlines
{"id": 1}{"id": 2} ❌ WRONG!{"id": 1}
{"id": 2} ✅ CORRECT!Wrapping in Array
[
{"id": 1},
{"id": 2}
] ❌ That's JSON, not NDJSON!Multi-line JSON Objects
{
"id": 1,
"name": "Alice"
} ❌ Each object must be on ONE line!{"id": 1, "name": "Alice"} ✅ Correct!Trailing Comma
{"id": 1},
{"id": 2}, ❌ No commas between lines!{"id": 1}
{"id": 2} ✅ Just newlines!
The Same Loop in Eight Languages
Reading NDJSON is the same three steps everywhere: open the file, take a line, parse it. Only the spelling changes. The language guide has full programs with error handling.
| Language | Read every record |
|---|---|
| Python | for line in open("data.jsonl"): record = json.loads(line) |
| Node.js | for await (const line of readline.createInterface({ input: fs.createReadStream("data.jsonl") })) { const record = JSON.parse(line); } |
| Go | scanner := bufio.NewScanner(f); for scanner.Scan() { json.Unmarshal(scanner.Bytes(), &record) } |
| Rust | for line in BufReader::new(file).lines() { let record: Value = serde_json::from_str(&line?)?; } |
| Java | try (MappingIterator<JsonNode> it = mapper.readerFor(JsonNode.class).readValues(new File("data.jsonl"))) { while (it.hasNext()) { JsonNode record = it.next(); } } (Jackson) |
| C# | foreach (var line in File.ReadLines("data.jsonl")) { var record = JsonSerializer.Deserialize<Record>(line); } |
| Ruby | File.foreach("data.jsonl") { |line| record = JSON.parse(line) } |
| PHP | while (($line = fgets($fh)) !== false) { $record = json_decode($line, true); } |
When Your First File Does Not Work

The very first line fails to parse
Two likely causes. The file starts with an invisible byte order mark, or it is really a JSON array and the first line is just [. Save as UTF-8 without BOM, and see converting a JSON array.
Only the last line fails
The writer was probably interrupted halfway through a record. Drop the incomplete line and carry on: every line before it is intact. This is the format working as designed.
How do I skip a bad line instead of crashing?
Wrap the parse of each line in its own error handler, record the line number and move on. Count the failures and stop if there are too many, so a wrong file does not pass silently.
My Go program stops on a long line
The default bufio.Scanner refuses lines over 64 KB. Give it a bigger buffer with scanner.Buffer, or read with bufio.Reader and ReadBytes.
Lines look fine but a field is missing
NDJSON has no schema, so a misspelled key is still valid. Check the fields you depend on as you read, or validate each line against a schema.
Windows line endings: problem or not?
Not for parsing. A JSON parser treats the carriage return as whitespace. It matters only when you compare files byte for byte, so pick one ending and keep it.
Quick Reference
Format Rules
- One JSON object per line
- Each line ends with newline (\n)
- No commas between lines
- No array wrapper
File Extensions
- .jsonl (recommended)
- .json (also works)
- .ndjson (same format)
- .jsonlines (valid)
When to Use
- Streaming data
- Large datasets
- ML training data
- Log files
Next Steps
Now that you understand the basics, explore these resources to master NDJSON: