Skip to content

Commit c6cb3d4

Browse files
martin-kochpboettch
authored andcommitted
mention default value processing in the README
1 parent 5e5918d commit c6cb3d4

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

README.md

+51
Original file line numberDiff line numberDiff line change
@@ -300,6 +300,57 @@ Supported formats: `date-time, date, time, email, hostname, ipv4, ipv6, uuid, re
300300
301301
More formats can be added in `src/string-format-check.cpp`. Please contribute implementions for missing json schema draft formats.
302302
303+
## Default value processing
304+
As a result of the validation, the library returns a json patch including the default values of the specified schema.
305+
306+
```C++
307+
#include <iostream>
308+
#include <nlohmann/json-schema.hpp>
309+
310+
using nlohmann::json;
311+
using nlohmann::json_schema::json_validator;
312+
313+
static const json rectangle_schema = R"(
314+
{
315+
"$schema": "http://json-schema.org/draft-07/schema#",
316+
"title": "A rectangle",
317+
"properties": {
318+
"width": {
319+
"$ref": "#/definitions/length",
320+
"default": 20
321+
},
322+
"height": {
323+
"$ref": "#/definitions/length"
324+
}
325+
},
326+
"definitions": {
327+
"length": {
328+
"type": "integer",
329+
"minimum": 1,
330+
"default": 10
331+
}
332+
}
333+
})"_json;
334+
335+
int main()
336+
{
337+
try {
338+
json_validator validator{rectangle_schema};
339+
/* validate empty json -> will be expanded by the default values defined in the schema */
340+
json rectangle = "{}"_json;
341+
const auto default_patch = validator.validate(rectangle);
342+
rectangle = rectangle.patch(default_patch);
343+
std::cout << rectangle.dump() << std::endl; // {"height":10,"width":20}
344+
} catch (const std::exception &e) {
345+
std::cerr << "Validation of schema failed: " << e.what() << "\n";
346+
return EXIT_FAILURE;
347+
}
348+
return EXIT_SUCCESS;
349+
}
350+
```
351+
The example above will output the specified default values `{"height":10,"width":20}` to stdout.
352+
> Note that the default value specified in a `$ref` may be overridden by the current instance location. Also note that this behavior will break draft-7, but it is compliant to newer drafts (e.g. `2019-09` or `2020-12`).
353+
303354
# Contributing
304355

305356
Before opening a pull request, please apply the coding style given in the

0 commit comments

Comments
 (0)