diff --git a/README.md b/README.md index c7e69c1..b9dd8d9 100644 --- a/README.md +++ b/README.md @@ -300,6 +300,57 @@ Supported formats: `date-time, date, time, email, hostname, ipv4, ipv6, uuid, re More formats can be added in `src/string-format-check.cpp`. Please contribute implementions for missing json schema draft formats. +## Default value processing +As a result of the validation, the library returns a json patch including the default values of the specified schema. + +```C++ +#include +#include + +using nlohmann::json; +using nlohmann::json_schema::json_validator; + +static const json rectangle_schema = R"( +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "A rectangle", + "properties": { + "width": { + "$ref": "#/definitions/length", + "default": 20 + }, + "height": { + "$ref": "#/definitions/length" + } + }, + "definitions": { + "length": { + "type": "integer", + "minimum": 1, + "default": 10 + } + } +})"_json; + +int main() +{ + try { + json_validator validator{rectangle_schema}; + /* validate empty json -> will be expanded by the default values defined in the schema */ + json rectangle = "{}"_json; + const auto default_patch = validator.validate(rectangle); + rectangle = rectangle.patch(default_patch); + std::cout << rectangle.dump() << std::endl; // {"height":10,"width":20} + } catch (const std::exception &e) { + std::cerr << "Validation of schema failed: " << e.what() << "\n"; + return EXIT_FAILURE; + } + return EXIT_SUCCESS; +} +``` +The example above will output the specified default values `{"height":10,"width":20}` to stdout. +> 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`). + # Contributing Before opening a pull request, please apply the coding style given in the