|
DAW JSON Link
|
daw::json::json_apply parses JSON values into the parameters of a callable and invokes the callable with those values. It is similar to std::apply, but the arguments come from a JSON document instead of a tuple.
Include either the main JSON Link header or the dedicated header:
When the callable takes one parameter, the complete JSON value is parsed as that parameter's type:
When the callable takes multiple parameters, the document is a JSON array and its elements are parsed in parameter order:
The return value is the result of invoking the callable.
By default, json_apply obtains the parameter types from the callable's signature. The usual JSON Link mappings apply, so parameters may be primitive types, containers, or mapped user-defined types.
CV and reference qualifiers do not affect how a parameter is parsed. For example, parameters such as std::size_t && and std::string_view && are parsed using their underlying value types before the callable is invoked.
A callable with no parameters is also supported:
The parameter types can be specified instead of inferred by passing a function type as the Signature template argument:
The explicit signature's parameter list determines the types used for parsing; json_apply returns the callable's actual result. The callable must currently have a single, non-template call operator; generic lambdas and types with overloaded call operators do not satisfy json_apply's callable constraint.
Pass a JSON path between the document and callable to apply the callable to a value within the document:
The value selected by the path is parsed according to the callable's parameters. See Parsing Individual Members for more about JSON paths.
Parser flags may be passed before the callable, with or without a JSON path:
The overloads are:
Signature is optional in every overload. See Parser Options for the available parsing policies and their safety implications.
The input does not have to be JSON text. An existing json_value can be passed to avoid locating the value again:
As with other non-owning JSON Link values, ensure that the source JSON remains alive while it is being referenced. See JSON Value for details about inspecting and retaining parsed values.
json_apply is particularly useful at IPC and RPC boundaries, where an array or value received as JSON maps naturally to a handler's parameters. It keeps the parsing types next to the code that consumes them and avoids a separate intermediate tuple or request object.