The <<ref_parse>> function offers a simple interface for converting a serialized JSON text to a <<ref_value>> in a single function call. This overload uses exceptions to indicate errors:
Unless otherwise specified, the parser in this library is strict. It recognizes only valid, standard JSON. The parser can be configured to allow certain non-standard extensions by filling in a <<ref_parse_options>> structure and passing it by value. By default all extensions are disabled:
When building with {cpp}20 or later, the use of https://en.cppreference.com/w/cpp/language/aggregate_initialization#Designated_initializers[designated initializers] with <<ref_parse_options>> is possible:
To use the <<ref_parser>>, declare an instance. Then call <<ref_parser_write>> once with the buffer containing representing the input JSON. Finally, call <<ref_parser_release>> to take ownership of the resulting <<ref_value>> upon success. This example persists the parser instance in a class member to reuse across calls:
Sometimes a protocol may have a JSON text followed by data that is in a different format or specification. The JSON portion can still be parsed by using the function <<ref_parser_write_some>>. Upon success, the return value will indicate the number of characters consumed from the input, which will exclude the non-JSON characters:
The <<ref_stream_parser>> implements a https://en.wikipedia.org/wiki/Online_algorithm[__streaming algorithm__]; it allows incremental processing of large JSON inputs using one or more contiguous character buffers. The entire input JSON does not need to be loaded into memory at once. A network server can use the streaming interface to process incoming JSON in fixed-size amounts, providing these benefits:
In the following example a JSON text is parsed from standard input a line at a time. Error codes are used instead. The function <<ref_stream_parser_finish>> is used to indicate the end of the input:
After default construction, or after <<ref_stream_parser_reset>> is called with no arguments, the <<ref_value>> produced after a successful parse operation uses the default memory resource. To use a different memory resource, call `reset` with the resource to use. Here we use a <<ref_monotonic_resource>>, which is optimized for parsing but not subsequent modification: