Programming Search⌘K

Formatcore

JSON Lines

Also called JSONL, NDJSON, newline-delimited JSON, line-delimited JSON.

JSON Lines is a text format with one JSON value on each line. A program appends a record with one write and reads the file one record at a time. Logs and data dumps often use it.

What it is

JSON Lines is a text format for a sequence of JSON values. Each line of the file holds one JSON value, and a line feed ends it. The site jsonlines.org describes the format with three requirements: the text is UTF-8, "Each Line is a Valid JSON Value", and the line terminator is \n1. The site calls it "a convenient format for storing structured data that may be processed one record at a time"1.

A JSON text is one value, so a list of records in plain JSON is one large array. A program must read to the closing ] before the array is complete, and it cannot add a record without a change to the end of the file. The Python documentation says the same thing in another way: JSON "is not a framed protocol", so repeated calls to dump() on one file give "an invalid JSON file"2. JSON Lines adds the frame. A writer appends a record with one write of one line, and a reader parses each line alone. The memory that a reader needs depends on the longest line, not on the size of the file.

This works because a JSON value never needs a raw line break. RFC 8259 allows white space, which includes the line feed, only between tokens3, and a string must escape the control characters below U+00203. A compact writer therefore puts each value on one line.

The same format has a second name, NDJSON (newline delimited JSON). The NDJSON specification gives the same rules for one JSON text on each line4. Google BigQuery, which loads these files, says that "The ndJSON format is the same as the JSON Lines format"5. Common uses are log files, exports of database tables, data sets for machine learning, and messages between processes through a pipe.

Syntax or structure

A file is a sequence of lines. The rules of the two descriptions are close:

Rule JSON Lines1 NDJSON4
Encoding UTF-8, with no byte order mark UTF-8
A line any JSON value, "but a blank line is not" a value a JSON text that conforms to RFC 8259
Line end \n; \r\n works because the JSON parser ignores the \r \n, which "MAY be preceded by a carriage return"
Last line a line terminator is "strongly recommended but not required" each text is "followed by the newline character"
Empty lines not valid the parser "MAY silently ignore empty lines"
File name .jsonl .ndjson
Media type application/jsonl, "not yet standardized" application/x-ndjson

The text below is a JSON Lines file with three records. Each value is an object, but the format allows any JSON value on a line.

{"id": 1, "msg": "start"}
{"id": 2, "msg": "two\nlines"}
{"id": 3, "city": "Zürich"}

The second record holds a line break in its string, written as the escape \n. The file still has three lines.

Examples

Python writes one line with json.dumps and a "\n", and reads the file with a loop over its lines. json.dumps with no indent "selects the most compact representation"2, which has no line break.

import json

records = [{"id": 1, "msg": "start"}, {"id": 2, "msg": "two\nlines"}, {"id": 3, "city": "Zürich"}]
text = "".join(json.dumps(r, ensure_ascii=False) + "\n" for r in records)
print(text.count("\n"), "lines")

for line in text.split("\n")[:-1]:
    print(json.loads(line))
Output
3 lines
{'id': 1, 'msg': 'start'}
{'id': 2, 'msg': 'two\nlines'}
{'id': 3, 'city': 'Zürich'}

The example files of this page show the same work in other languages:

  • JavaScript. JSON.stringify writes one line, and readline with for await reads the file line by line. The option crlfDelay: Infinity makes \r followed by \n "always be considered a single newline"6.
  • Go. Encoder.Encode "writes the JSON encoding of v to the stream, followed by a newline character"7, so a sequence of calls writes JSON Lines. A bufio.Scanner reads the lines. Its default limit for one line is MaxScanTokenSize = 64 * 1024 bytes8, and Scanner.Buffer sets a larger limit.
  • C#. JsonSerializer.Serialize writes one line. DeserializeAsyncEnumerable with the parameter topLevelValues, "Whether to deserialize from a sequence of top-level JSON values"9, reads the file as a sequence of values.
  • Python. A reader that reports the line number of a bad line, and a file that a second writer appends to.

On the command line, jq reads a sequence of JSON values with no special option. The option --compact-output writes "each JSON object on a single line"10, and --slurp reads "the entire input stream into a large array"10. So jq -c . converts a sequence of pretty JSON values to JSON Lines, and jq -s . converts JSON Lines to one JSON array.

PythonGitHub
import json
import os
import tempfile


def read_jsonl(path):
    """Yields the values of a JSON Lines file. A bad line raises ValueError with its line number."""
    with open(path, encoding="utf-8") as f:
        for number, line in enumerate(f, start=1):
            try:
                yield json.loads(line)
            except json.JSONDecodeError as error:
                raise ValueError(f"line {number}: {error.msg}") from None


fd, path = tempfile.mkstemp(suffix=".jsonl")
with os.fdopen(fd, "w", encoding="utf-8", newline="\n") as f:
    for event in [{"level": "info", "n": 1}, {"level": "warn", "n": 2}]:
        f.write(json.dumps(event) + "\n")
with open(path, "a", encoding="utf-8", newline="\n") as f:
    f.write(json.dumps({"level": "info", "n": 3}) + "\n")
    f.write("\n")

try:
    for value in read_jsonl(path):
        print(value)
except ValueError as error:
    print("ValueError:", error)
finally:
    os.remove(path)
Output
{'level': 'info', 'n': 1}
{'level': 'warn', 'n': 2}
{'level': 'info', 'n': 3}
ValueError: line 4: Expecting value
  • Verdict: stdlib. json.dumps writes each value on one line, and a loop over an open file gives one line at a time, so the memory holds one record. The reader keeps a line number and puts it in the error, because a JSON Lines file can have millions of lines. The file is opened again in append mode for a third record, which is the main reason to use JSON Lines: an append adds a record with no change to the lines before it. The blank line at the end is not a JSON value, so the strict reader reports it.
using System.Text;
using System.Text.Json;

string path = Path.GetTempFileName();
try
{
    var records = new[] { new Event("info", 1), new Event("warn", 2) };
    // Serialize writes no line break inside a value, so each record is one line.
    File.WriteAllLines(path, records.Select(e => JsonSerializer.Serialize(e, EventJson.Default.Event)), new UTF8Encoding(false));
    Console.Write(File.ReadAllText(path));

    // With topLevelValues: true, the serializer reads a sequence of values instead of one array.
    using FileStream stream = File.OpenRead(path);
    await foreach (Event? e in JsonSerializer.DeserializeAsyncEnumerable(stream, EventJson.Default.Event, topLevelValues: true))
    {
        Console.WriteLine(e);
    }
}
finally
{
    File.Delete(path);
}

record Event(string Level, int N);

[System.Text.Json.Serialization.JsonSourceGenerationOptions(PropertyNamingPolicy = System.Text.Json.Serialization.JsonKnownNamingPolicy.CamelCase)]
[System.Text.Json.Serialization.JsonSerializable(typeof(Event))]
partial class EventJson : System.Text.Json.Serialization.JsonSerializerContext;
Output
{"level":"info","n":1}
{"level":"warn","n":2}
Event { Level = info, N = 1 }
Event { Level = warn, N = 2 }
  • Verdict: stdlib. JsonSerializer.Serialize writes each record with no line break, and File.WriteAllLines adds the line ends. A source-generated JsonSerializerContext gives the type information. DeserializeAsyncEnumerable with topLevelValues: true reads the values one after the other from the stream, with no array around them.
JavaScriptGitHub
import { createReadStream, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { createInterface } from "node:readline";

// JSON.stringify writes U+2028 and U+2029 as themselves. The escapes \u2028 and \u2029 are also valid JSON.
const toLine = (value) =>
  JSON.stringify(value).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029") + "\n";

async function readLines(path) {
  // crlfDelay: Infinity makes \r\n one line end, also when the bytes come in two reads.
  const lines = createInterface({ input: createReadStream(path), crlfDelay: Infinity });
  const out = [];
  for await (const line of lines) out.push(line);
  return out;
}

const dir = mkdtempSync(join(tmpdir(), "jsonl-"));
try {
  const events = [{ level: "info", note: "a\u2028b" }, { level: "warn", n: 2 }];
  const last = '{"level": "info", "n": 3}\r\n';

  const raw = join(dir, "raw.jsonl");
  writeFileSync(raw, events.map((e) => JSON.stringify(e) + "\n").join("") + last);
  console.log("raw:", (await readLines(raw)).length, "lines for 3 records");

  const safe = join(dir, "safe.jsonl");
  writeFileSync(safe, events.map(toLine).join("") + last);
  let number = 0;
  for (const line of await readLines(safe)) {
    const value = JSON.parse(line);
    console.log(++number, value.level, value.note === "a\u2028b");
  }
} finally {
  rmSync(dir, { recursive: true, force: true });
}
Output
raw: 4 lines for 3 records
1 info true
2 warn false
3 info false
  • Verdict: stdlib. JSON.stringify writes one line, and readline.createInterface with for await reads one line at a time from a stream. The last record ends with \r\n, and with crlfDelay: Infinity the reader sees one line end. JSON.stringify writes U+2028 in the first record as itself, not as an escape, and readline ends a line at U+2028 and U+2029 as well as at \n and \r. So the raw file gives 4 lines for 3 records. The function toLine writes the two characters as the escapes \u2028 and \u2029, which are valid JSON, and then each record is one line.
package main

import (
	"bufio"
	"encoding/json"
	"fmt"
	"os"
	"path/filepath"
	"strings"
)

type Event struct {
	Level string `json:"level"`
	Note  string `json:"note"`
}

func main() {
	dir, _ := os.MkdirTemp("", "jsonl-")
	defer os.RemoveAll(dir)
	path := filepath.Join(dir, "events.jsonl")

	f, _ := os.Create(path)
	enc := json.NewEncoder(f) // Encode writes each value and a newline.
	enc.Encode(Event{"info", "short"})
	enc.Encode(Event{"warn", strings.Repeat("x", 70000)})
	f.Close()

	for _, max := range []int{bufio.MaxScanTokenSize, 1 << 20} {
		f, _ := os.Open(path)
		sc := bufio.NewScanner(f)
		sc.Buffer(make([]byte, 0, 4096), max)
		for sc.Scan() {
			var e Event
			if err := json.Unmarshal(sc.Bytes(), &e); err != nil {
				fmt.Println(err)
				break
			}
			fmt.Println(max, e.Level, len(e.Note))
		}
		fmt.Println(max, "error:", sc.Err())
		f.Close()
	}
}
Output
65536 info 5
65536 error: bufio.Scanner: token too long
1048576 info 5
1048576 warn 70000
1048576 error: <nil>
  • Verdict: stdlib. json.Encoder writes each value and a newline. bufio.Scanner reads one line at a time, and json.Unmarshal parses it. The second record is longer than 64 KiB, so with the default limit Scan stops and Err returns bufio.Scanner: token too long. With a limit of 1 MiB the scanner reads both records.

Versions

There is no RFC for JSON Lines or NDJSON. Each is a short specification on a web site, and the site jsonlines.org says that the media type application/jsonl "is not yet standardized"1. The NDJSON specification has the version 1.0.04.

RFC 7464 defines a related IETF standard, JSON text sequences, with the media type application/json-seq11. Each JSON text starts with the ASCII record separator RS (0x1E) and ends with a line feed11. With RS, a parser can find the start of the next value after a value that is cut short, and a value can contain line breaks. The RFC says that a large sequence of values in one JSON array is "difficult to work with", and that a sequence can be parsed "incrementally without having to have a streaming parser"11. jq writes and reads this format with the option --seq10.

Pitfalls

  • A pretty-printed value breaks the format. An indent puts line breaks inside the value, so each line is only part of a value:

This code runs but gives a wrong answer on purpose.

import json

line = json.dumps({"id": 1, "tags": ["a", "b"]}, indent=2) + "\n"
print(line.count("\n"), "lines for one record")
try:
    json.loads(line.split("\n")[0])
except json.JSONDecodeError as error:
    print("JSONDecodeError:", error.msg)
Output
7 lines for one record
JSONDecodeError: Expecting property name enclosed in double quotes

Write each value in its most compact form. Do not pass an indent.

  • str.splitlines splits on more than the line feed. The method splits on \n, \r and also on \v, \f, \x1c, \x1d, \x1e, \x85, \u2028 and \u202912. JSON allows U+2028 and U+2029 in a string with no escape3, and json.dumps with ensure_ascii=False writes them as themselves:

This code runs but gives a wrong answer on purpose.

import json

text = json.dumps({"note": "a\u2028b"}, ensure_ascii=False) + "\n"
print(len(text.splitlines()), "parts from splitlines")
print(len(text.split("\n")[:-1]), "line from split on \\n")
try:
    json.loads(text.splitlines()[0])
except json.JSONDecodeError as error:
    print("JSONDecodeError:", error.msg)
Output
2 parts from splitlines
1 line from split on \n
JSONDecodeError: Unterminated string starting at

Split on \n only, or iterate over the lines of a file opened in text mode, as in the examples.

  • A long line stops the Go scanner. A bufio.Scanner returns the error bufio.Scanner: token too long for a line longer than its limit8. The Go example shows this error at the default limit of 64 KiB, and the fix with Scanner.Buffer.
  • The last line is incomplete. If a writer stops in the middle of a record, the file ends with part of a line. With a line terminator after each value, a reader can tell a complete last record from a cut one: a complete file ends with \n, and the text after the last \n is incomplete.
import json

text = '{"id": 1}\n{"id": 2}\n{"id": 3, "msg": "sto'
*complete, rest = text.split("\n")
for line in complete:
    print(json.loads(line))
print("incomplete:", repr(rest))
Output
{'id': 1}
{'id': 2}
incomplete: '{"id": 3, "msg": "sto'
  • Two writers share one file. Each writer must write a whole line in one write, or lock the file. Two writers that write parts of lines can mix the bytes of two records on one line.
  • Empty lines. A blank line is not valid JSON Lines1, but NDJSON lets a parser skip it4. A strict reader reports an error, as in the Python example. Choose one rule and document it.
  • A byte order mark. JSON Lines does not allow one1. A strict parser rejects a first line that starts with one.

Tools and libraries

  • Python: the json module and a loop over the lines of the file.
  • JavaScript (Node.js): JSON.parse, JSON.stringify and the readline module6.
  • Go: json.Encoder to write, and bufio.Scanner with json.Unmarshal, or one json.Decoder for the whole file, to read78.
  • C#: JsonSerializer.Serialize, and JsonSerializer.DeserializeAsyncEnumerable with topLevelValues9.
  • jq for the command line10.
  • Data systems such as Google BigQuery load newline-delimited JSON5.

The page Stream-parse a large JSON file reads one large JSON array, the other way to store many records in JSON. Read a file line by line shows the line loop of each language.

References

  1. JSON Lines, jsonlines.org, the three requirements; Conventions
  2. The Python Standard Library, json, Python 3.14, json.dump, the note on framing; json.dumps, indent; JSONDecodeError
  3. T. Bray (Ed.), RFC 8259: The JavaScript Object Notation (JSON) Data Interchange Format, December 2017, 2 JSON Grammar; 7 Strings
  4. T. Hoeger, C. Dew, F. Pauls, J. Wilson, NDJSON: Newline delimited JSON, version 1.0.0, 2014, 3.1 Serialization; 3.2 Parsing; 3.3 MediaType and File Extensions
  5. Google Cloud documentation, Loading JSON data from Cloud Storage, the introduction
  6. Node.js documentation, Readline, readline.createInterface, crlfDelay; rl[Symbol.asyncIterator]()
  7. Go standard library, package encoding/json, Encoder.Encode
  8. Go standard library, package bufio, MaxScanTokenSize; ErrTooLong; Scanner.Buffer; ScanLines
  9. .NET API reference, JsonSerializer.DeserializeAsyncEnumerable, Overloads; the parameter topLevelValues
  10. jq manual, Invoking jq, --compact-output, --slurp, --seq
  11. N. Williams, RFC 7464: JavaScript Object Notation (JSON) Text Sequences, February 2015, 1 Introduction; 2.1 JSON Text Sequence Parsing; 2.2 JSON Text Sequence Encoding
  12. The Python Standard Library, Built-in Types, Python 3.14, str.splitlines, the table of line boundaries

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source