JSON5 vs JSONL and NDJSON

Similar names, different jobs: one is written by people, the others are streamed by programs.

JSON5 is a friendlier syntax for a single document, with comments and trailing commas. JSON Lines and NDJSON are ways to store or stream many strict JSON values, with exactly one complete value on each line.

This page untangles the names, checks each specification, explains whether a line may use JSON5 syntax, and gives tested Node.js code for turning a hand-written array into line-delimited records and reading them back safely.

A commented JSON5 document on a desk beside a conveyor carrying one JSON record per line

TL;DR: The "5" in JSON5 is not related to the "L" in JSONL. Use JSON5 for one document that a person edits, such as a config file. Use JSON Lines (also called NDJSON, with small differences) for logs, exports and streams where each line is a complete strict JSON value. Do not put JSON5 syntax in a .jsonl file.

Going deeper on the line formats? Our sister sites JSONL.rest and NDJSON.com are full references for JSON Lines and NDJSON, with guides, examples and a validator.

Compare icon

Which Is Which

Four names turn up in the same searches. Three of them are about putting many JSON values into one file or stream. JSON5 is the odd one out: it changes what a single value may look like.

NameWhat it isSpecificationExtensionMedia type named by the spec
JSON5Extended JSON syntax for one documentVersion 1.0.0, March 2018.json5No entry in the IANA application registry
JSON Lines (JSONL)One JSON value per linejsonlines.org, unversioned.jsonlapplication/jsonl, described as not yet standardized
NDJSONNewline-delimited JSON for streamsndjson-spec 1.0.0, last updated October 2014.ndjsonapplication/x-ndjson
JSON text sequencesEach value prefixed by a record separator byteRFC 7464, February 2015None registeredapplication/json-seq

Here is the visible difference. A JSON5 file is one value, laid out for a reader:

// events.json5 - fixtures, edited by hand [ { id: 1, type: 'signup', user: 'ada' }, // retried once { id: 2, type: 'payment', user: 'lin', cents: 0x1F4 }, { id: 3, type: 'note', text: 'first\nsecond', }, ]

The same data as JSON Lines is three independent values with no enclosing array and no commas between them:

{"id":1,"type":"signup","user":"ada"} {"id":2,"type":"payment","user":"lin","cents":500} {"id":3,"type":"note","text":"first\nsecond"}

The file as a whole is therefore not a JSON document, and not a JSON5 document either. Feeding it to JSON.parse fails with "Unexpected non-whitespace character after JSON" at line 2, and JSON5.parse reports an invalid { character at the same spot. You have to split first and parse each line.

Stream icon

JSON Lines and NDJSON: One Format, Two Names

JSON Lines and NDJSON (newline-delimited JSON) came out of separate communities in 2013 and describe the same thing: one valid JSON value per line, with lines separated by \n. In practice a parser that reads one reads the other. The differences are small and mostly about labels and edge cases.

JSON LinesNDJSON
Specificationjsonlines.org, unversionedndjson-spec 1.0.0 (created July 2013, last updated October 2014)
File extension.jsonl ("may be saved with").ndjson (SHOULD)
Media typeapplication/jsonl, which the site says "is not yet standardized"application/x-ndjson (SHOULD); an x- type, outside the IANA registry
EncodingUTF-8 required, and no byte order markSerialized data "MUST use the UTF8 encoding"
Line endings\n; \r\n also works because JSON ignores surrounding white spaceWriters use \n, optionally preceded by \r; parsers must accept both
Blank linesNot allowed: "a blank line is not" a valid valueA parser MAY silently ignore empty lines, if it documents that it does
Final newline"Strongly recommended but not required"Every value is followed by a newline
Where you see itAI tooling: OpenAI Batch API input and output files, and Anthropic Message Batches results, are .jsonlLogging and streaming: the Elasticsearch bulk API body is NDJSON, sent as application/json or application/x-ndjson

Two practical rules cover nearly every case: write UTF-8 with a newline after every value including the last, and never write blank lines. Files written that way satisfy both specifications. When reading, accept \r\n and decide deliberately whether to skip blank lines or treat them as errors.

Use the GitHub specification for NDJSON. The old ndjson.org domain no longer hosts the specification; as of November 29, 2026 it serves unrelated content. The ndjson-spec repository is the source. For full references, see our sister sites JSONL.rest and NDJSON.com.

Question icon

Why the Names Confuse People

  • Suffixes look like versions or variants. JSON5 reads like "JSON version 5", and JSONL like another dialect in the same series. Neither reading is right. The JSON5 syntax draws on ECMAScript 5.1, and the L stands for Lines.
  • One idea has several names. The jsonlines.org page itself says the format is also called newline-delimited JSON, while a separate NDJSON specification has its own extension and media type.
  • JSON5 mentions multiple lines. It lets a string continue across lines with a trailing backslash. That is about wrapping one long string and has nothing to do with line-delimited records.
  • All are described as "JSON, but". The useful question is what changed: the grammar of a value (JSON5) or the framing around many values (the rest).

If your search was really about comments in JSON, you probably want JSON5 or JSONC. If it was about large files, log shipping or processing records one at a time, you want line-delimited JSON.

List icon

JSON Lines: Three Requirements

The JSON Lines page, maintained by Ian Ward, is short. It presents the format for record-at-a-time processing, Unix-style pipelines, log files and message passing between cooperating processes. It states three requirements:

  1. UTF-8 encoding. A byte order mark must not be included. Authors may escape non-ASCII characters to keep a file plain ASCII.
  2. Each line is a valid JSON value. Objects and arrays are most common, but any value is permitted, including null. A blank line is not valid.
  3. The line terminator is \n. \r\n also works, because JSON parsers ignore surrounding whitespace. A terminator after the last value is strongly recommended but not required; if present, it must be the final byte of the file.

The page also records conventions: the .jsonl extension, stream compression such as gzip (giving .jsonl.gz), a possible application/jsonl media type that has not been standardized, and counting the first value as value 1.

"Valid JSON value" is the phrase that matters here. JSON, as specified in RFC 8259, has no comments, no trailing commas, no single-quoted strings, and no NaN or Infinity. JSON Lines inherits every one of those limits.

Stream icon

NDJSON: the Stream Specification

The NDJSON specification lives in the ndjson/ndjson-spec repository. Its header gives version 1.0.0, created July 2013 and last updated October 2014. It aims at delivering multiple JSON texts over stream protocols such as TCP or Unix pipes, and uses the RFC 2119 keywords:

  • Each JSON text MUST conform to RFC 8259 and MUST be followed by a newline. A carriage return MAY precede the newline.
  • JSON texts MUST NOT contain newlines or carriage returns, and data MUST be UTF-8.
  • Parsers MUST accept both \n and \r\n and SHOULD raise an error for unparsable text.
  • A parser MAY silently ignore empty lines, but that behavior MUST be documented and SHOULD be configurable.
QuestionJSON LinesNDJSON
Newline after the last valueStrongly recommendedRequired
Blank linesNot validA parser may ignore them, if documented
Extension.jsonl.ndjson
Media typeapplication/jsonl (not standardized)application/x-ndjson

A writer that emits strict JSON objects, one per line, with a final newline and no blank lines satisfies both. Neither media type appears in the IANA application registry, so agree on a Content-Type with whatever service you are calling.

Specification icon

RFC 7464: JSON Text Sequences

The IETF Standards Track answer to the same problem is RFC 7464, written by Nicolas Williams. It is not JSON Lines. Every element starts with the ASCII record separator, byte 0x1E, and ends with a line feed. Because a raw record separator cannot appear inside JSON text, it marks element boundaries unambiguously, and a value may be pretty-printed across several lines.

The design is about recovery. If a writer crashes halfway through an element, the parser should skip to the next record separator and carry on. Top-level numbers, true, false and null have no closing delimiter, so a parser must check that whitespace follows them and drop any that might be cut short: a surviving 123 could have been 1234. This small Node.js parser applies those rules:

const RS = String.fromCharCode(0x1e); function parseSeq(text) { const out = []; // slice(1): anything before the first separator is not an element for (const part of text.split(RS).slice(1)) { if (part === '') continue; let value; try { value = JSON.parse(part); } catch { console.warn('skipped malformed element'); continue; } const selfDelimited = value !== null && (typeof value === 'object' || typeof value === 'string'); if (!selfDelimited && !/[ \t\r\n]$/.test(part)) { console.warn('dropped possibly truncated value:', part); continue; } out.push(value); } return out; } // the last element, 56, has no line feed after it console.log(parseSeq(RS + '{"a":1}\n' + RS + '1234\n' + RS + '56')); // dropped possibly truncated value: 56 // [ { a: 1 }, 1234 ]

A JSON Lines reader will choke on the separator bytes, and a sequence parser expects them, so the two are not interchangeable.

Layers icon

Streaming Records vs Authored Documents

The design choices follow from who writes the file. Line-delimited JSON assumes a program appends records and another program consumes them, possibly while the file is still growing. JSON5 assumes a person opens an editor, changes a setting and explains why in a comment. Its project documentation describes it as meant for hand-written files such as configuration, and not for machine-to-machine communication.

NeedJSON5JSON Lines / NDJSON
CommentsYesNo
Append a record without rewriting the fileNo: an enclosing array must stay closedYes: write one more line
Process record by recordNot with JSON5.parse, which takes the whole stringYes, split on newlines
Effect of one corrupt recordThe whole parse failsOther lines can still be read, if your reader allows it
Values spread over several lines for readabilityYesNo
Readable by any strict JSON parser, per valueNoYes

If a single JSON5 document is genuinely too large to load at once, that is a signal to change formats rather than to hunt for a clever parser. The streaming tutorial goes further into that trade-off.

Warning icon

Can a JSONL Line Be JSON5?

Mechanically, you can write a file where each line is a JSON5 value and read it with JSON5.parse in a loop. It is then no longer JSON Lines or NDJSON, because both require strict JSON on every line. A strict reader will say so. Python 3.14:

echo "{ id: 1, type: 'signup' }" | python -m json --json-lines # Expecting property name enclosed in double quotes: line 1 column 3 (char 2)

Node.js agrees: JSON.parse rejects the same line with "Expected property name or '}'". There are further reasons not to do it:

  • Comment lines are not values. JSON5.parse('// only a comment') throws "invalid end of input". A comment at the end of a record parses, but a comment on its own line breaks a line-by-line reader.
  • Block comments and values cannot span lines once you split on newlines, which removes most of what makes JSON5 pleasant to write.
  • Silent drift. Because JSON is valid JSON5, your own reader accepts a mix of both, and nobody notices until another consumer fails.
  • Special numbers travel badly. A line holding NaN or Infinity has no strict JSON form at all.

Watch for the accidental version. JSON5.stringify called without an indent argument also produces one line per value, so a logger using it looks plausible and emits invalid JSON Lines:

JSON5.stringify([{ id: 1, tags: ['a'] }]); // [{id:1,tags:['a']}] unquoted keys, single quotes: not JSON JSON.stringify([{ id: 1, tags: ['a'] }]); // [{"id":1,"tags":["a"]}] correct for a JSONL line

If a team really wants an annotated, line-oriented private format, give it a different extension, document it, and convert to strict JSON Lines at the boundary. The cleaner design is to keep authored sources in JSON5 and generate the .jsonl file.

Convert icon

Converting a JSON5 Array to JSONL

The conversion is: parse the document, confirm it is an array, serialize each element with the built-in JSON.stringify, and end each line with \n. Two details deserve code. JSON.stringify writes NaN and Infinity as null without complaint, and it leaves the characters U+2028 and U+2029 unescaped.

// to-jsonl.mjs - usage: node to-jsonl.mjs input.json5 output.jsonl import { readFileSync, writeFileSync } from 'node:fs'; import JSON5 from 'json5'; const [input, output] = process.argv.slice(2); const data = JSON5.parse(readFileSync(input, 'utf8')); if (!Array.isArray(data)) { throw new TypeError('Top-level value must be an array'); } // JSON.stringify silently writes NaN and Infinity as null, so refuse them. function strict(key, value) { if (typeof value === 'number' && !Number.isFinite(value)) { throw new RangeError(`Key "${key}": ${value} cannot be written as JSON`); } return value; } // U+2028 and U+2029 are legal inside JSON strings, but some line readers split on them. const escapes = { '\u2028': '\\u2028', '\u2029': '\\u2029' }; const lines = data.map((record) => JSON.stringify(record, strict).replace(/[\u2028\u2029]/g, (c) => escapes[c]) ); writeFileSync(output, lines.map((line) => line + '\n').join(''), 'utf8'); console.log(`Wrote ${lines.length} records to ${output}`);

Run against the events.json5 file shown at the top, with the json5 2.2.3 package on Node.js 24:

$ node to-jsonl.mjs events.json5 events.jsonl Wrote 3 records to events.jsonl

The output is the three-line file shown earlier. The comments are gone and the hex literal 0x1F4 has become 500. An input of [{ ratio: NaN }] stops with RangeError: Key "ratio": NaN cannot be written as JSON, and a top-level object stops with the TypeError. Nothing is written in either case. Integers beyond JavaScript's safe range are rounded during parsing, before this script sees them, so keep large identifiers as strings.

Going back

To produce an editable document from records, parse each line and serialize the array once, with indentation:

const records = readFileSync('events.jsonl', 'utf8') .split('\n') .filter(Boolean) // drops the empty piece after the final newline .map((line) => JSON.parse(line)); writeFileSync('events.json5', JSON5.stringify(records, null, 2) + '\n');

This writes unquoted keys, single-quoted strings and trailing commas. It cannot recover the old comments, and filter(Boolean) also forgives blank lines in the middle of a file, which strict JSON Lines does not allow.

Node.js logo

Reading Lines Safely in Node.js

The obvious tool, node:readline, has a catch. The API documentation describes end of line as \n, \r or \r\n, but in the Node.js 24 source the line-ending pattern also includes U+2028 and U+2029. Both characters are allowed unescaped inside a JSON string, and JSON.stringify emits them raw. In our test, one valid record containing U+2028 came out of readline as two broken pieces, while splitting on \n returned it whole.

// the file holds one record: JSON.stringify({ text: 'a\u2028b' }) readline // [ '{"text":"a', 'b"}' ] two lines, neither parses split('\n') // one record (plus '' after the final newline)

The streaming reader below splits only on \n, holds one partial line between chunks, and reports the line number of a failure. A trailing \r needs no special handling because JSON.parse treats it as whitespace.

import { createReadStream } from 'node:fs'; function parseLine(line, n) { try { return JSON.parse(line); } catch (cause) { throw new SyntaxError(`line ${n}: ${cause.message}`, { cause }); } } export async function* readJsonl(path) { let rest = ''; let n = 0; for await (const chunk of createReadStream(path, 'utf8')) { const parts = (rest + chunk).split('\n'); rest = parts.pop(); for (const part of parts) yield parseLine(part, ++n); } if (rest !== '') yield parseLine(rest, ++n); }

Given a file with two good CRLF lines followed by a truncated third, it yields both records and then throws an error that begins line 3:. It has no maximum line length; add one before reading untrusted input, since a file with no newline would be buffered in full.

Tools icon

How Common Tools Treat These Formats

ToolDocumented behavior
jqRuns a filter once per input value; --slurp gathers all input into one array; --seq reads and writes application/json-seq, skipping unparsable input with a warning
Python logoPython json command line--json-lines parses every input line as a separate JSON object (added in 3.8)
Elasticsearch bulk APITakes NDJSON action and source lines; the final line must end with a newline; accepts application/json or application/x-ndjson
json5 command lineTakes one document from a file or standard input; use it on the source file, not on a JSONL file

The Elasticsearch case shows why the small print matters: the same page tells curl users to send files with --data-binary, because -d does not preserve newlines. When newlines are the framing, anything that rewrites whitespace, including a pretty-printer or an editor's format-on-save, corrupts the data. Exclude .jsonl and .ndjson files from such tools. For JSON5 formatting and checks, see the command-line tools.

Target icon

Choosing a Format

Your situationUse
Application or build configuration edited by peopleJSON5, if the consuming tool reads it
Application logs written continuouslyJSON Lines or NDJSON
Large export or import, processed record by recordJSON Lines or NDJSON
A service that names .ndjson or application/x-ndjsonNDJSON, with a final newline
A stream where truncated writes must be detected and skipped under an IETF standardRFC 7464 text sequences
One request or response bodyPlain JSON
Hand-maintained test records fed to a streaming consumerAuthor in JSON5, generate JSONL

These formats combine well in one project: a commented pipeline.json5 can configure a program whose input and output are .jsonl files. New to the syntax? Start with the learning guide, or see how it compares with other formats on the comparison overview.

Question icon

Common Questions

Are JSONL and NDJSON the same thing?

Nearly, in practice. Both put one JSON value on each line. They differ on the final newline, blank lines, the file extension and the suggested media type.

Is there an official format that combines JSON5 with line delimiting?

None of the specifications on this page defines one. The JSON5 specification describes a document holding a single value, and the line-delimited specifications require strict JSON.

How do I add a comment to a JSONL file?

You cannot do it within the format. Put the note in a field of the record, in a separate README, or in the JSON5 source that generates the file.

Is a one-record JSONL file also valid JSON5?

Yes. A single strict JSON value, with or without a final newline, is valid JSON5. With two or more records the file is not a single document and the parser rejects it.

Can a record contain a line break inside a string?

Yes, written as the escape \n. JSON requires control characters in strings to be escaped, so the encoded record stays on one line.