Add simple example just for checking validity of schemas

This commit is contained in:
Tristan Penman 2024-12-22 19:43:37 +11:00
parent b151d1e99a
commit 0a15cf4fe9
2 changed files with 53 additions and 0 deletions

View File

@ -231,6 +231,10 @@ if(valijson_BUILD_EXAMPLES)
examples/array_iteration_template_fn.cpp
)
add_executable(check_schema
examples/check_schema.cpp
)
add_executable(object_iteration
examples/object_iteration.cpp
)
@ -265,6 +269,7 @@ if(valijson_BUILD_EXAMPLES)
target_link_libraries(external_schema ${Boost_LIBRARIES})
target_link_libraries(array_iteration_basics jsoncpp)
target_link_libraries(array_iteration_template_fn jsoncpp)
target_link_libraries(check_schema jsoncpp)
target_link_libraries(object_iteration jsoncpp)
target_link_libraries(json_pointers)
endif()

48
examples/check_schema.cpp Normal file
View File

@ -0,0 +1,48 @@
/**
* @file
*
* @brief Loads a schema then exits. Exit code will be 0 if the schema is
* valid, and 1 otherwise. This example uses jsoncpp to parse the
* schema document.
*/
#include <iostream>
#include <valijson/adapters/jsoncpp_adapter.hpp>
#include <valijson/utils/jsoncpp_utils.hpp>
#include <valijson/schema.hpp>
#include <valijson/schema_parser.hpp>
using std::cerr;
using std::endl;
using valijson::Schema;
using valijson::SchemaParser;
using valijson::adapters::JsonCppAdapter;
int main(int argc, char *argv[])
{
if (argc != 2) {
cerr << "Usage: " << argv[0] << " <schema document>" << endl;
return 1;
}
// Load the document containing the schema
Json::Value schemaDocument;
if (!valijson::utils::loadDocument(argv[1], schemaDocument)) {
cerr << "Failed to load schema document." << endl;
return 1;
}
Schema schema;
SchemaParser parser;
JsonCppAdapter adapter(schemaDocument);
try {
parser.populateSchema(adapter, schema);
} catch (std::exception &e) {
cerr << "Failed to parse schema: " << e.what() << endl;
return 1;
}
return 0;
}