| 112 | // Until 0.174.0, throw a `schema_error` instead of returning json::null() |
| 113 | |
| 114 | void resolve_uri_example() |
| 115 | { |
| 116 | std::string main_schema = R"( |
| 117 | { |
| 118 | "$id" : "https://www.example.com/main", |
| 119 | "$schema": "https://json-schema.org/draft/2020-12/schema", |
| 120 | "$id": "http://localhost:1234/draft2020-12/object", |
| 121 | "type": "object", |
| 122 | "properties": { |
| 123 | "name": {"$ref": "/name-defs.json#/$defs/orNull"} |
| 124 | } |
| 125 | } |
| 126 | )"; |
| 127 | |
| 128 | std::string root_dir = "./input/jsonschema"; |
| 129 | auto resolver = [&](const jsoncons::uri& uri) -> json |
| 130 | { |
| 131 | std::cout << "Requested URI: " << uri.string() << "\n"; |
| 132 | std::cout << "base: " << uri.base().string() << ", path: " << uri.path() << "\n\n"; |
| 133 | |
| 134 | std::string pathname = root_dir + uri.path(); |
| 135 | |
| 136 | std::fstream is(pathname.c_str()); |
| 137 | if (!is) |
| 138 | { |
| 139 | return json::null(); |
| 140 | } |
| 141 | |
| 142 | return json::parse(is); |
| 143 | }; |
| 144 | |
| 145 | json schema = json::parse(main_schema); |
| 146 | |
| 147 | // Data |
| 148 | json data = json::parse(R"( |
| 149 | { |
| 150 | "name": { |
| 151 | "name": null |
| 152 | } |
| 153 | } |
| 154 | )"); |
| 155 | |
| 156 | try |
| 157 | { |
| 158 | // Throws schema_error if JSON Schema compilation fails |
| 159 | jsonschema::json_schema<json> compiled = jsonschema::make_json_schema(schema, resolver); |
| 160 | |
| 161 | auto report = [](const jsonschema::validation_message& msg) -> jsonschema::walk_result |
| 162 | { |
| 163 | std::cout << msg.instance_location().string() << ": " << msg.message() << "\n"; |
| 164 | for (const auto& detail : msg.details()) |
| 165 | { |
| 166 | std::cout << " " << detail.message() << "\n"; |
| 167 | } |
| 168 | return jsonschema::walk_result::advance; |
| 169 | }; |
| 170 | |
| 171 | // Will call report function object for each schema violation |