Files
json/docs/mkdocs/docs/features/parsing/index.md
T
Niels LohmannandClaude Sonnet 5.5 33f15727ce Parse JSON in one block of memory with a fused pointer-based parser (#6031)
* Parse JSON in one block of memory with a fused pointer-based parser

The parser and the lexer exchange one token at a time, and the lexer keeps
its state (the current character, a pending unget, where the token starts)
in members, which every character pays for: json::accept() of twitter.json
took 2.8x as long as json_document::accept(). detail::contiguous_parser
reads text in one block of memory through a local pointer, with the
grammar, the whitespace and the tokens in one loop (after yyjson's reader),
and drives a SAX handler: parse()'s DOM handler, accept()'s handler, or the
user's handler of sax_parse(). It is used with the default options (no
callback, no comments, no trailing commas; sax_parse() with strict = true).

Errors are reported by the library parser, so the exception, its message and
its position stay the same. contiguous_parser stops at the token that the
library parser would reject, before reporting it, so the events up to the
error are the same; then:
- parse() runs the library parser with a handler that only reports the
  error (json_sax_error_reporter), with the lexer of parse(), which is
  instantiated anyway;
- sax_parse() runs it with a handler that forwards only parse_error() to
  the user's handler (json_sax_error_forwarder), so no event arrives twice;
- accept() returns the verdict.
A handler that returns false stops the parse as before. An error at the end
of a large input costs parse() about 1.2x of what it cost before.

On an Apple M1 Max: accept() 1.6-2.0x as fast, parse() 10-16% faster,
ordered_json 11-16%, sax_parse() with a user's handler 1.36-1.46x, small
messages 12-22% (parse()) and 2.1-2.4x (accept()). On x86-64 (GCC 15,
Clang 21): accept() 1.6-1.9x, parse() 5-17%, ordered_json 12-19%,
sax_parse() 1.32-1.57x. A translation unit that parses a string compiles 3%
(-O0) and 9% (-O2) slower.

unit-contiguous_parser.cpp compares the contiguous path with the byte path
(std::list iterators) on corner cases, generated documents, their
truncations and mutations, deep nesting, and narrow number types: the same
values with the same number types and float bits, exception messages,
accept() verdicts and sax_parse() events.

Signed-off-by: Niels Lohmann <mail@nlohmann.me>

* Fix CI: unused parameter without exceptions, cpplint, BUILD.bazel

- json_sax_error_reporter::parse_error: mark the exception unused, as
  JSON_THROW does not use it with JSON_NOEXCEPTION
- unit-contiguous_parser.cpp: compare the exceptions of both paths only
  when exceptions are enabled (invalid input aborted the test otherwise)
- silence cpplint's readability/braces false positives on the if
  statements inside the parser's macros
- add contiguous_parser.hpp to BUILD.bazel

Signed-off-by: Niels Lohmann <mail@nlohmann.me>

* accept(): skip digits without computing their value

accept() needs the value of a number only for a float whose exponent may
reach the largest value. skip_digits() finds the end of the digits without
the multiply-adds of accumulate_digits(), and once an 8-byte word fails the
digit test, the remaining loop needs no bounds check: a non-digit is in
that word. The value is computed afterwards for the rare floats that need
it.

accept() of canada.json: -16 % on Apple M1, -22 % with GCC 15 and -21 %
with Clang 21 on x86-64; files with many numbers -9 to -15 %.

Signed-off-by: Niels Lohmann <mail@nlohmann.me>

* Tests: mark parser callback in unit-contiguous_parser noexcept

Fixes the -Werror=noexcept failure with GCC 26 (ci_test_standards_gcc (26)).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N5NasEsrzHhSNouxSoEwqz
Signed-off-by: Niels Lohmann <mail@nlohmann.me>

* Tests: sweep_allocator::construct() accepts pointers to const

Recent libc++ (emsdk latest) probes construct(const T*, const T&) in an
unevaluated context while checking for trivial copies; the static_cast to
void* in the noexcept specification then fails to compile.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N5NasEsrzHhSNouxSoEwqz
(cherry picked from commit 794bf70823c12a2a1cb2a8a95f34dfb6357746a8)
Signed-off-by: Niels Lohmann <mail@nlohmann.me>

* Tests: guard sweep_allocator::construct() against const types instead of const_cast

The const_cast added in the previous commit is rejected by
cppcoreguidelines-pro-type-const-cast (clang-tidy). Make construct() not
viable for const U instead, which is what libc++ probes for.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N5NasEsrzHhSNouxSoEwqz
(cherry picked from commit de099fa607001b710862fd1bbecef3609c54cbc4)
Signed-off-by: Niels Lohmann <mail@nlohmann.me>

* Fix CI: astyle and clang-tidy for sweep_allocator::construct()

astyle 3.4.13 reformats the enable_if<!...> default template argument
(Check amalgamation). Delete the const overload instead, which makes the
libc++ probe for const objects fail in the SFINAE context just the same
and needs no <type_traits>.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N5NasEsrzHhSNouxSoEwqz
Signed-off-by: Niels Lohmann <mail@nlohmann.me>

* Contiguous parser: review fixes (wording, macros, diagnostic positions)

- "default parser" instead of "library parser" in comments and tests
- the three comments in json.hpp say the same thing
- current() replaces the repeated `p != end ? *p : 0`
- the backslashes of each macro are aligned
- the docs say that JSON_DIAGNOSTIC_POSITIONS turns the fast path off

Signed-off-by: Niels Lohmann <mail@nlohmann.me>

---------

Signed-off-by: Niels Lohmann <mail@nlohmann.me>
Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-10 07:08:44 +01:00

12 KiB

Parsing

This library can create a JSON value from a wide range of inputs. This page gives an overview of the available parsing functions and how they behave; the linked pages go into more detail.

flowchart LR
    I["JSON input"] --> P["parse()"]
    I --> S["sax_parse()"]
    I --> A["accept()"]
    P -->|"optional parser callback filters values"| D["basic_json value (DOM)"]
    S --> H["events delivered to a user SAX handler"]
    A --> V["bool: is the input valid JSON?"]

The three entry points for parsing: `parse()` builds a `basic_json` value, optionally filtered by a parser callback, `sax_parse()` delivers events to a SAX handler, and `accept()` only checks whether the input is valid.

Input

The parse function reads a JSON value from an input. The input can be

  • a string (#!cpp std::string, C string, or string literal),
  • a wide string (#!cpp std::u16string, #!cpp std::u32string, or #!cpp std::wstring, or a wide string literal),
  • a #!cpp std::istream (e.g., an #!cpp std::ifstream reading from a file),
  • a #!cpp FILE* pointer,
  • a pair of iterators over a contiguous range (e.g., a #!cpp std::vector<std::uint8_t>), or
  • a contiguous container.
// parse from a string
json j = json::parse(R"({"happy": true, "pi": 3.141})");

// parse from a file
std::ifstream f("example.json");
json data = json::parse(f);

See Reading and writing files for checking that the file was opened and for writing files safely.

The input must be encoded in UTF-8; other encodings are not supported. The exception is wide-character input, which is read as UTF-16 or UTF-32 — depending on the character type — and converted to UTF-8; see the parse page for an example. A single input may contain only one JSON value. Inputs consisting of multiple values separated by newlines are handled by the JSON Lines format; input that arrives in chunks or contains several values is covered in Large, streamed, and partial input.

By default, the library rejects comments and trailing commas. Both can be enabled with parameters of the parse function — see comments and trailing commas.

basic_json_document::parse accepts the same inputs with the same options, but keeps the result in a document rather than in a basic_json value; see Documents and views below.

Strictness and trailing data

parse reads a single JSON value and requires the whole input to be consumed: any non-whitespace data after the value is reported as a parse error. Use it when you want to guarantee that an input is exactly one complete JSON document.

operator>> follows relaxed #!cpp std::istream semantics instead: it parses one JSON value and leaves the stream positioned right after it, without requiring the rest of the stream to be consumed. This is what makes it possible to read several concatenated values from the same stream, but it also means that "a valid document followed by trailing bytes" is accepted rather than rejected. If you are validating conformance, or need to reject any input that is not exactly one JSON document, prefer parse.

When using operator>> to read several concatenated values this way, a value that is a number must be followed by whitespace, because operator>> consumes the character that terminates a number, unless JSON_PRECISE_STREAM_POSITION is defined to 1 — see the operator>> notes for details and examples.

Input sources and performance

All inputs produce the same values and the same exceptions, but they are read in different ways, which makes some of them faster than others:

input how it is read
strings, string views, string literals, contiguous containers, pointer or iterator ranges over contiguous memory the whole input is scanned in bulk: runs of string characters, numbers, and indentation are recognized several bytes at a time
#!cpp std::istream (#!cpp std::ifstream, #!cpp std::istringstream, ...) the characters the stream buffer holds are scanned in bulk like a string; the stream buffer is asked for more when they are used up
#!cpp FILE* with glibc and the Apple C library, the characters the FILE holds in its buffer are scanned in bulk like a stream's; elsewhere one character at a time; the file is locked once for the whole parse
other iterator ranges (e.g., #!cpp std::list<char>, #!cpp std::istreambuf_iterator<char>), wide strings one character at a time

Input in one block of memory is read even faster with the default options (no parser callback, no comments, no trailing commas, and for sax_parse() strict = true): parse(), accept(), and sax_parse() then read the grammar and the tokens in one loop over the memory. Only after an error do parse() and sax_parse() read the input again, to report the error exactly as before. This faster path is not used when JSON_DIAGNOSTIC_POSITIONS is enabled, because the positions are recorded by the default parser: the input is then parsed as before, at the same speed as before.

Parsing a file from a #!cpp std::ifstream therefore takes about 1.15 to 1.45 times as long as reading the whole file into a #!cpp std::string first and parsing that, but it needs no memory for a copy of the file. The stream is never read ahead: after parsing, it is positioned exactly as if every character had been read one at a time, so operator>> can still read several values from one stream (see also JSON Lines).

This does not hold for json_document: it reads a stream into a buffer it owns, so the stream saves no memory, and reading the file into a #!cpp std::string yourself and borrowing it is about 6 to 12 % faster.

Two macros switch these optimizations off without changing any result: JSON_DISABLE_STREAM_BULK_SCAN for stream buffers that do not follow the usual std::streambuf contract, and JSON_DISABLE_UNLOCKED_FILE_IO for programs in which another thread must use the same #!cpp FILE object while it is parsed.

Where the target has them, strings are scanned with vector instructions: SSE2 on x86-64 (and SSSE3 for UTF-8 text, when the CPU has it) and NEON on AArch64. JSON_NO_SIMD selects portable code instead, again without changing any result.

SAX vs. DOM parsing

The library offers two parsing models, and a third, read-only alternative:

  • DOM parsing (the default): the complete input is read and stored as an in-memory basic_json value that can be traversed and modified freely. This is what parse does, and it is the right choice for most use cases.

  • SAX parsing: instead of building a value, the parser reports events (such as "a string was read" or "an object started") to a handler that you implement. This avoids building the full value in memory and is useful for very large inputs or when you only need to extract parts of the input. See the SAX interface for details and sax_parse for the API.

  • Document and views (#!cpp <nlohmann/json_view.hpp>, added in version 3.13.0): json_document::parse reads the same JSON grammar but builds a flat, read-only index of the values instead of a basic_json tree. Strings and floating-point numbers are read from the text on demand, and only the parts you materialize() become basic_json values. This avoids most of the work when you need only a few values from a large or frequently parsed text; see Zero-copy JSON views. It is read-only, so use parse when you need to modify the value.

You can influence a DOM parse without switching to the SAX interface by passing a parser callback, which is called during parsing and can, for example, discard parts of the input.

Documents and views

A third model sits between DOM and SAX: basic_json_document::parse parses the input into a document that keeps the text and a flat index of the values in it, and basic_json_view gives read-only access to the values through that index. The whole input is validated during parsing, but only integers and strings that contain escape sequences are converted right away (the strings into a buffer owned by the document). Floating-point numbers and all other strings stay in the source text and are only converted when they are read, which is faster and uses less memory than building a tree of basic_json values when only parts of the document are needed. A document can also be modified in place, and it can be saved and loaded again without parsing it.

#include <nlohmann/json_view.hpp>

json_document doc = json_document::parse(R"({"happy": true, "pi": 3.141})");
std::cout << doc.root()["happy"].get<bool>() << '\n';

See Zero-copy JSON views for the concept and the trade-offs.

Exceptions

When the input is not valid JSON, the parse function throws an exception by default. If exceptions are undesired or unavailable, the parser can instead return a discarded value, or accept can be used to only check whether an input is valid JSON. See parsing and exceptions for the available options.

See also