CCF
Loading...
Searching...
No Matches
json_schema.h
Go to the documentation of this file.
1// Copyright (c) Microsoft Corporation. All rights reserved.
2// Licensed under the Apache 2.0 License.
3#pragma once
4
5#include <nlohmann/json.hpp>
6#include <optional>
7#include <string>
8#include <valijson/adapters/nlohmann_json_adapter.hpp>
9#include <valijson/schema.hpp>
10#include <valijson/schema_parser.hpp>
11#include <valijson/utils/nlohmann_json_utils.hpp>
12#include <valijson/validator.hpp>
13
14namespace json
15{
16 static std::optional<std::string> validate_json(
17 const nlohmann::json& input_json, const nlohmann::json& schema_json)
18 {
19 valijson::Schema schema;
20 valijson::SchemaParser parser;
21 valijson::Validator validator;
22
23 valijson::adapters::NlohmannJsonAdapter schema_adapter(schema_json);
24 valijson::adapters::NlohmannJsonAdapter target_adapter(input_json);
25
26 parser.populateSchema(schema_adapter, schema);
27
28 valijson::ValidationResults results;
29 if (!validator.validate(schema, target_adapter, &results))
30 {
31 std::string validation_error_msg;
32 valijson::ValidationResults::Error error;
33 size_t error_num = 0;
34 while (results.popError(error))
35 {
36 std::string error_ctx;
37 for (auto const& c : error.context)
38 {
39 error_ctx += c;
40 }
41 validation_error_msg += fmt::format(
42 "\nError #{}:\n context: {}\n message: {}",
43 error_num,
44 error_ctx,
45 error.description);
46 ++error_num;
47 }
48 return validation_error_msg;
49 }
50
51 return std::nullopt;
52 }
53}
Definition json_schema.h:15