### Install and Import Valijson with CMake Source: https://github.com/tristanpenman/valijson/blob/master/README.md Install Valijson using CMake's install command from its build tree. Subsequently, import the installed library into other CMake projects using `find_package(Valijson)` and link it to your executable. ```bash # Install Valijson git clone --recurse-submodules --depth=1 git@github.com:tristanpenman/valijson.git cd valijson mkdir build cd build cmake .. cmake --install . ``` ```cmake # Import installed valijson and link it to your executable find_package(valijson REQUIRED) add_executable(executable main.cpp) target_link_libraries(executable valijson) ``` -------------------------------- ### Configure Installation Rules Source: https://github.com/tristanpenman/valijson/blob/master/CMakeLists.txt Defines installation paths for headers and the exported CMake configuration. ```cmake install(DIRECTORY include/ DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}) install(TARGETS valijson EXPORT valijsonConfig DESTINATION ${CMAKE_INSTALL_LIBDIR} ) install(EXPORT valijsonConfig DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/valijson" ) ``` -------------------------------- ### Retrieve Instance Collection Source: https://github.com/tristanpenman/valijson/blob/master/doc/specifications/draft-zyp-json-schema-03.txt Example of a GET request response for a collection of instance resources. ```http GET /Resource/ [ { "id": "thing", "upId": "parent" }, { "id": "thing2", "upId": "parent" } ] ``` -------------------------------- ### Build Valijson Examples and Test Suite with CMake Source: https://github.com/tristanpenman/valijson/blob/master/README.md Commands to build the examples and test suite for Valijson using CMake. Ensure you are in the build directory. ```bash # Build examples and test suite mkdir build cd build cmake .. -Dvalijson_BUILD_TESTS=ON -Dvalijson_BUILD_EXAMPLES=ON make ``` -------------------------------- ### URI Reference Resolution Examples (Normal) Source: https://github.com/tristanpenman/valijson/blob/master/doc/specifications/rfc3986-uri.txt Examples demonstrating the transformation of relative URI references to their target URIs based on a defined base URI. Covers various path and fragment scenarios. ```uri "g:h" = "g:h" "g" = "http://a/b/c/g" "./g" = "http://a/b/c/g" "g/" = "http://a/b/c/g/" "/g" = "http://a/g" "//g" = "http://g" "?y" = "http://a/b/c/d;p?y" "g?y" = "http://a/b/c/g?y" "#s" = "http://a/b/c/d;p?q#s" "g#s" = "http://a/b/c/g#s" "g?y#s" = "http://a/b/c/g?y#s" ";x" = "http://a/b/c/;x" "g;x" = "http://a/b/c/g;x" "g;x?y#s" = "http://a/b/c/g;x?y#s" "" = "http://a/b/c/d;p?q" "." = "http://a/b/c/" "./" = "http://a/b/c/" ".." = "http://a/b/" "../" = "http://a/b/" "../g" = "http://a/b/g" "../.." = "http://a/" "../../" = "http://a/" "../../g" = "http://a/g" ``` -------------------------------- ### Example Valid JSON Document Source: https://context7.com/tristanpenman/valijson/llms.txt A sample JSON document that conforms to the provided example schema. ```json { "name": "John Doe", "email": "john@example.com", "age": 30 } ``` -------------------------------- ### Configure CMake with Homebrew Qt5 on macOS Source: https://github.com/tristanpenman/valijson/blob/master/README.md Example of setting CMAKE_PREFIX_PATH when building with CMake on macOS if Qt 5 is installed via Homebrew. This helps CMake locate the Qt installation. ```bash mkdir build cd build cmake .. -DCMAKE_PREFIX_PATH=$(brew --prefix qt5) make ``` -------------------------------- ### Valijson Benchmark Output Example Source: https://github.com/tristanpenman/valijson/blob/master/README.md Example output from the Valijson benchmark program, indicating the number of documents validated, total time taken, documents per second, and the total number of validation failures encountered. ```text Validated 2000000 documents in 6.63379 seconds. Documents: 2, Iterations: 1000000 (301487 per second) 1000000 validation failure(s) encountered. ``` -------------------------------- ### JSON Document Example Source: https://github.com/tristanpenman/valijson/blob/master/doc/specifications/rfc6901-json-pointer.txt An example JSON document used to illustrate JSON Pointer evaluation. ```json { "foo": ["bar", "baz"], "": 0, "a/b": 1, "c%d": 2, "e^f": 3, "g|h": 4, "i\\j": 5, "k\"l": 6, " ": 7, "m~n": 8 } ``` -------------------------------- ### Example JSON Instance Source: https://github.com/tristanpenman/valijson/blob/master/doc/specifications/draft-luff-json-hyper-schema-00.txt A sample JSON object that conforms to the previously defined article schema. ```json { "id": 15, "title": "Example data", "authorId": 105, "imgData": "iVBORw...kJggg==" } ``` -------------------------------- ### Query Product Collection Source: https://github.com/tristanpenman/valijson/blob/master/doc/specifications/draft-zyp-json-schema-03.txt Example of a URI query string for filtering products by name. ```text /Product/?name=Slinky ``` -------------------------------- ### Root Schema Example Source: https://github.com/tristanpenman/valijson/blob/master/doc/specifications/draft-zyp-json-schema-04.txt An example of a JSON Schema with no nested subschemas. This serves as a basic root schema. ```json { "title": "root" } ``` -------------------------------- ### Integrate with RapidJSON Parser Source: https://context7.com/tristanpenman/valijson/llms.txt Illustrates using the RapidJSON adapter to parse schemas and documents for validation. Includes an example of parsing JSON directly from a string. ```cpp #include #include #include #include #include #include using valijson::Schema; using valijson::SchemaParser; using valijson::Validator; using valijson::adapters::RapidJsonAdapter; // Load documents from files rapidjson::Document schemaDoc, targetDoc; valijson::utils::loadDocument("schema.json", schemaDoc); valijson::utils::loadDocument("target.json", targetDoc); // Parse schema Schema schema; SchemaParser parser; RapidJsonAdapter schemaAdapter(schemaDoc); parser.populateSchema(schemaAdapter, schema); // Validate Validator validator; RapidJsonAdapter targetAdapter(targetDoc); bool valid = validator.validate(schema, targetAdapter, nullptr); // Parse JSON from string rapidjson::Document doc; doc.Parse(R"({"name": "John", "age": 30})"); if (!doc.HasParseError()) { RapidJsonAdapter adapter(doc); // Use adapter for validation... } ``` -------------------------------- ### Remove Dot Segments Algorithm - Step-by-Step Example Source: https://github.com/tristanpenman/valijson/blob/master/doc/specifications/rfc3986-uri.txt Illustrates the step-by-step application of the remove_dot_segments algorithm using two buffers, showing the state of the output and input buffers. ```text STEP OUTPUT BUFFER INPUT BUFFER 1 : /a/b/c/./../../g 2E: /a /b/c/./../../g 2E: /a/b /c/./../../g 2E: /a/b/c /./../../g 2B: /a/b/c /../../g 2C: /a/b /../g 2C: /a /g 2E: /a/g ``` -------------------------------- ### Example 'self' link schema Source: https://github.com/tristanpenman/valijson/blob/master/doc/specifications/draft-luff-json-hyper-schema-00.txt This example shows a basic JSON Hyper-Schema with a 'self' link relation where the href is dynamically set by an 'id' property. ```json { "links": [{ "rel": "self", "href": "{id}" }] } ``` -------------------------------- ### Example JSON Hyper-Schema Links Source: https://github.com/tristanpenman/valijson/blob/master/doc/specifications/draft-luff-json-hyper-schema-00.txt This example demonstrates how to define 'self', 'up', and 'children' link relations within a JSON Hyper-Schema. These links are used to specify URIs for related resources, such as the resource itself, its parent, or a collection of its children. ```json { "links": [{ "rel": "self", "href": "{id}" }, { "rel": "up", "href": "{upId}" }, { "rel": "children", "href": "?upId={id}" }] } ``` -------------------------------- ### JSON String to JSON Pointer Evaluation Source: https://github.com/tristanpenman/valijson/blob/master/doc/specifications/rfc6901-json-pointer.txt Examples demonstrating how JSON strings evaluate to specific values within the example JSON document using JSON Pointers. ```json "" // the whole document ``` ```json "/foo" ["bar", "baz"] ``` ```json "/foo/0" "bar" ``` ```json "/" 0 ``` ```json "/a~1b" 1 ``` ```json "/c%d" 2 ``` ```json "/e^f" 3 ``` ```json "/g|h" 4 ``` ```json "/i\\j" 5 ``` ```json "/k\"l" 6 ``` ```json "/ " 7 ``` ```json "/m~0n" 8 ``` -------------------------------- ### Define submission link properties Source: https://github.com/tristanpenman/valijson/blob/master/doc/specifications/draft-luff-json-hyper-schema-00.txt Example of a schema using 'encType' and 'method' to define how a client can query a server. ```json { "links": [{ "encType": "application/x-www-form-urlencoded", "method": "GET", "href": "/Product/", "properties": { "name": { "description": "name of the product" } } }] } ``` -------------------------------- ### Configure Valijson CMake Project Source: https://github.com/tristanpenman/valijson/blob/master/CMakeLists.txt Initializes the project, sets C++17 standards, and defines build options for tests, examples, and dependency handling. ```cmake cmake_minimum_required(VERSION 3.10.0) project(valijson) set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_EXTENSIONS OFF) set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_CURRENT_SOURCE_DIR}/cmake") option(valijson_BUILD_EXAMPLES "Build valijson examples." FALSE) option(valijson_BUILD_TESTS "Build valijson test suite." FALSE) option(valijson_EXCLUDE_BOOST "Exclude Boost when building test suite." FALSE) option(valijson_USE_EXCEPTIONS "Use exceptions in valijson and included libs." TRUE) option(valijson_USE_BOOST_REGEX "Use boost::regex instead of std::regex internally." FALSE) mark_as_advanced(valijson_USE_BOOST_REGEX) ``` -------------------------------- ### Define a Product Schema Source: https://github.com/tristanpenman/valijson/blob/master/doc/specifications/draft-zyp-json-schema-03.txt Example of a JSON Schema defining properties, types, requirements, and link relations for a product resource. ```json { "name":"Product", "properties":{ "id":{ "type":"number", "description":"Product identifier", "required":true }, "name":{ "description":"Name of the product", "type":"string", "required":true }, "price":{ "required":true, "type": "number", "minimum":0, "required":true }, "tags":{ "type":"array", "items":{ "type":"string" } } }, "links":[ { "rel":"full", "href":"{id}" }, { "rel":"comments", "href":"comments/?id={id}" } ] } ``` -------------------------------- ### Define Submission Link with Enctype Source: https://github.com/tristanpenman/valijson/blob/master/doc/specifications/draft-zyp-json-schema-03.txt Example of a schema link definition using application/x-www-form-urlencoded for querying. ```json { "links":[ { "enctype":"application/x-www-form-urlencoded", "method":"GET", "href":"/Product/", "properties":{ "name":{"description":"name of the product"} } } ] } ``` -------------------------------- ### Define links with media types Source: https://github.com/tristanpenman/valijson/blob/master/doc/specifications/draft-luff-json-hyper-schema-00.txt Example of a schema defining multiple links with different relation types and media types. ```json { "links": [{ "rel": "self", "href": "/{id}/json" }, { "rel": "alternate", "href": "/{id}/html", "mediaType": "text/html" }, { "rel": "alternate", "href": "/{id}/rss", "mediaType": "application/rss+xml" }, { "rel": "icon", "href": "{id}/icon", "mediaType": "image/*" }] } ``` -------------------------------- ### Define an object schema with property constraints Source: https://github.com/tristanpenman/valijson/blob/master/doc/specifications/draft-fge-json-schema-validation-00.txt Example schema demonstrating the use of properties, patternProperties, and additionalProperties to restrict object structure. ```json { "properties": { "p1": {} }, "patternProperties": { "p": {}, "[0-9]": {} }, "additionalProperties": false } ``` -------------------------------- ### Define Links Keyword in Schema Source: https://github.com/tristanpenman/valijson/blob/master/doc/specifications/draft-luff-json-hyper-schema-00.txt A minimal schema example illustrating the use of the 'links' keyword to associate multiple link description objects with an instance. ```json { "title": "Schema defining links", "links": [ { "rel": "full", "href": "{id}" }, { "rel": "parent", "href": "{parent}" } ] } ``` -------------------------------- ### Create and Manage Schema with Valijson Source: https://context7.com/tristanpenman/valijson/llms.txt Demonstrates creating a root schema, sub-schemas, adding constraints, and setting metadata using the Schema class. Ensure necessary headers are included. ```cpp #include #include using valijson::Schema; using valijson::Subschema; // Create a new empty schema Schema schema; // Create sub-schemas owned by the root schema const Subschema *categorySchema = schema.createSubschema(); const Subschema *priceSchema = schema.createSubschema(); // Add constraints to sub-schemas via the root schema valijson::constraints::TypeConstraint typeConstraint; typeConstraint.addNamedType(valijson::constraints::TypeConstraint::kString); schema.addConstraintToSubschema(typeConstraint, categorySchema); // Set metadata on sub-schemas schema.setSubschemaTitle(categorySchema, "Category"); schema.setSubschemaDescription(categorySchema, "Product category"); schema.setSubschemaId(categorySchema, "#/definitions/category"); // Access the root sub-schema const Subschema *root = schema.root(); // Access shared empty sub-schema (for constraints that need an empty schema) const Subschema *empty = schema.emptySubschema(); ``` -------------------------------- ### Example Invalid JSON Document Source: https://context7.com/tristanpenman/valijson/llms.txt A sample JSON document that violates the provided example schema, demonstrating potential validation errors. ```json { "name": "", "age": -5 } // Errors: missing required 'email', 'name' minLength violated, 'age' minimum violated ``` -------------------------------- ### Example JSON Schema Source: https://context7.com/tristanpenman/valijson/llms.txt This is an example JSON schema defining the structure and constraints for a JSON object, including required properties and data types. ```json { "type": "object", "properties": { "name": { "type": "string", "minLength": 1 }, "age": { "type": "integer", "minimum": 0 }, "email": { "type": "string", "format": "email" } }, "required": ["name", "email"] } ``` -------------------------------- ### Build JSON Inspector Application Source: https://github.com/tristanpenman/valijson/blob/master/README.md Instructions for building the Qt-based JSON Inspector application. Navigate to the inspector directory, create a build directory, and run CMake and make. ```bash cd inspector mkdir build cd build cmake .. make ``` -------------------------------- ### JSON Schema Example Source: https://github.com/tristanpenman/valijson/blob/master/doc/specifications/draft-zyp-json-schema-03.txt An example of a JSON Schema definition for a 'person' object, illustrating the use of 'type', 'object', 'properties', 'string', and 'integer' attributes. ```APIDOC ## JSON Schema Example ### Description An example JSON Schema definition for a 'person' object. ### Request Example ```json { "description":"A person", "type":"object", "properties":{ "name":{"type":"string"}, "age" :{ "type":"integer", "maximum":125 } } } ``` ``` -------------------------------- ### Navigate JSON with Pointers and References Source: https://context7.com/tristanpenman/valijson/llms.txt Demonstrates resolving JSON pointers within a document and parsing JSON reference strings for schema composition. ```cpp #include #include #include #include using valijson::adapters::RapidJsonAdapter; // Load a JSON document rapidjson::Document doc; doc.Parse(R"({ "users": [ {"name": "Alice", "email": "alice@example.com"}, {"name": "Bob", "email": "bob@example.com"} ], "config": { "timeout": 30, "retries": 3 } })"); RapidJsonAdapter root(doc); // Resolve JSON pointers auto usersAdapter = valijson::internal::json_pointer::resolveJsonPointer( root, "/users"); // Points to users array auto firstUserName = valijson::internal::json_pointer::resolveJsonPointer( root, "/users/0/name"); // Points to "Alice" auto timeout = valijson::internal::json_pointer::resolveJsonPointer( root, "/config/timeout"); // Points to 30 // Extract values if (firstUserName.maybeString()) { std::string name = firstUserName.asString(); // "Alice" } // Parse JSON Reference strings std::string ref = "#/definitions/user"; auto maybePointer = valijson::internal::json_reference::getJsonReferencePointer(ref); if (maybePointer) { std::string pointer = *maybePointer; // "/definitions/user" } // Get URI from JSON Reference (for remote references) std::string remoteRef = "https://example.com/schemas/user.json#/definitions/address"; auto maybeUri = valijson::internal::json_reference::getJsonReferenceUri(remoteRef); if (maybeUri) { std::string uri = *maybeUri; // "https://example.com/schemas/user.json" } ``` -------------------------------- ### URI Fragment Identifier to JSON Pointer Evaluation Source: https://github.com/tristanpenman/valijson/blob/master/doc/specifications/rfc6901-json-pointer.txt Examples showing how URI fragment identifiers evaluate to specific values within the example JSON document. ```uri # // the whole document ``` ```uri #/foo ["bar", "baz"] ``` ```uri #/foo/0 "bar" ``` ```uri #/ 0 ``` ```uri #/a~1b 1 ``` ```uri #/c%25d 2 ``` -------------------------------- ### Define JSON Hyper-Schema with Links and Media Source: https://github.com/tristanpenman/valijson/blob/master/doc/specifications/draft-luff-json-hyper-schema-00.txt A comprehensive schema example demonstrating property definitions, media type specification for binary data, and link relations using instance values. ```json { "title": "Written Article", "type": "object", "properties": { "id": { "title": "Article Identifier", "type": "number" }, "title": { "title": "Article Title", "type": "string" }, "authorId": { "type": "integer" }, "imgData": { "title": "Article Illustration (small)", "type": "string", "media": { "binaryEncoding": "base64", "type": "image/png" } } }, "required" : ["id", "title", "authorId"], "links": [ { "rel": "full", "href": "{id}" }, { "rel": "author", "href": "/user?id={authorId}" } ] } ``` -------------------------------- ### Schema with Inline Dereferencing Example Source: https://github.com/tristanpenman/valijson/blob/master/doc/specifications/draft-zyp-json-schema-04.txt This example illustrates inline dereferencing where a fragment reference ('#inner') resolves to a subschema defined within the same document. Implementations supporting inline dereferencing can use this. ```json { "id": "http://some.site/schema#", "not": { "$ref": "#inner" }, "definitions": { "schema1": { "id": "#inner", "type": "boolean" } } } ``` -------------------------------- ### Load JSON Document with RapidJSON Adapter Source: https://github.com/tristanpenman/valijson/blob/master/doc/design/adapters.md Demonstrates how to load a JSON document from a file using the `loadDocument` utility function provided by the RapidJSON adapter. This utility simplifies the process of parsing JSON files. ```cpp rapidjson::Document document; if (!valijson::utils::loadDocument(filename, document)) { std::cerr << "Failed to load document " << filename << std::endl; return; } ``` -------------------------------- ### URI Reference Resolution Examples (Abnormal) Source: https://github.com/tristanpenman/valijson/blob/master/doc/specifications/rfc3986-uri.txt Examples of abnormal URI reference resolutions, including excessive '..' segments and unusual '.' and '..' component usage. Parsers must handle these consistently. ```uri "../../../g" = "http://a/g" "../../../../g" = "http://a/g" ``` ```uri "/./g" = "http://a/g" "/../g" = "http://a/g" "g." = "http://a/b/c/g." ".g" = "http://a/b/c/.g" "g.." = "http://a/b/c/g.." "..g" = "http://a/b/c/..g" ``` ```uri ". /../g" = "http://a/b/g" "./g/." = "http://a/b/c/g/" "g/./h" = "http://a/b/c/g/h" "g/../h" = "http://a/b/c/h" "g;x=1/./y" = "http://a/b/c/g;x=1/y" "g;x=1/../y" = "http://a/b/c/y" ``` -------------------------------- ### Programmatically Build a Schema with Valijson Source: https://github.com/tristanpenman/valijson/blob/master/README.md Demonstrates memory management when building a schema with custom code, ensuring all allocated memory is freed when the root schema goes out of scope. ```cpp { // Root schema object that manages memory allocated for // constraints or sub-schemas Schema schema; // Allocating memory for a sub-schema returns a const pointer // which allows inspection but not mutation. This memory will be // freed only when the root schema goes out of scope const Subschema *subschema = schema.createSubschema(); { // Limited scope, for example purposes // Construct a constraint on the stack TypeConstraint typeConstraint; typeConstraint.addNamedType(TypeConstraint::kString); // Constraints are added to a sub-schema via the root schema, // which will make a copy of the constraint schema.addConstraintToSubschema(typeConstraint, subschema); // Constraint on the stack goes out of scope, but the copy // held by the root schema continues to exist } // Include subschema in properties constraint PropertiesConstraint propertiesConstraint; propertiesConstraint.addPropertySubschema("description", subschema); // Add the properties constraint schema.addConstraint(propertiesConstraint); // Root schema goes out of scope and all allocated memory is freed } ``` -------------------------------- ### SchemaParser Entry Point: populateSchema Source: https://github.com/tristanpenman/valijson/blob/master/doc/design/schema_parser.md The main entry point for parsing schemas. Typically invoked with default values for fetch/free document arguments, disabling external reference resolution. ```c++ template void populateSchema( const AdapterType &node, Schema &schema, typename FunctionPtrs::FetchDoc fetchDoc = nullptr, typename FunctionPtrs::FreeDoc freeDoc = nullptr); ``` -------------------------------- ### SchemaParser Entry Point: populateSchema() Source: https://github.com/tristanpenman/valijson/blob/master/doc/design/schema_parser.md The primary entry point for parsing JSON schemas. It initializes caches and calls `resolveThenPopulateSchema` to begin the recursive parsing process. External document fetching can be enabled via optional arguments. ```APIDOC ## populateSchema() ### Description This function serves as the entry point for parsing JSON schemas. It sets up document and schema caches for efficiency and cycle detection, then delegates the main parsing logic to `resolveThenPopulateSchema`. ### Method `template void populateSchema(const AdapterType &node, Schema &schema, typename FunctionPtrs::FetchDoc fetchDoc = nullptr, typename FunctionPtrs::FreeDoc freeDoc = nullptr)` ### Parameters - **node** (AdapterType) - The root node of the JSON schema document. - **schema** (Schema&) - The Schema object to populate with the parsed schema. - **fetchDoc** (FetchDoc) - Optional callback function to fetch external documents (defaults to nullptr). - **freeDoc** (FreeDoc) - Optional callback function to free fetched documents (defaults to nullptr). ``` -------------------------------- ### Represent a Comment Payload Source: https://github.com/tristanpenman/valijson/blob/master/doc/specifications/draft-luff-json-hyper-schema-00.txt Example JSON payload for a POST request to create a new comment. ```json { "message": "This is an example comment" } ``` -------------------------------- ### Example JSON Instance Data with Links Source: https://github.com/tristanpenman/valijson/blob/master/doc/specifications/draft-luff-json-hyper-schema-00.txt This JSON data represents a collection of instance resources, each with an 'id' and 'upId'. The structure is intended to be used with a schema that defines 'self' and 'up' link relations, allowing for navigation to individual resources and their parent. ```json GET /Resource/ [ { "id": "thing", "upId": "parent" }, { "id": "thing2", "upId": "parent" } ] ``` -------------------------------- ### Define a union type schema Source: https://github.com/tristanpenman/valijson/blob/master/doc/specifications/draft-zyp-json-schema-03.txt Example of a schema that allows an instance to be either a string or a number. ```json {"type":["string","number"]} ``` -------------------------------- ### Define an object instance for validation Source: https://github.com/tristanpenman/valijson/blob/master/doc/specifications/draft-fge-json-schema-validation-00.txt Example JSON object instance used to test against the defined schema. ```json { "p1": true, "p2": null, ``` -------------------------------- ### Define Schema Links Source: https://github.com/tristanpenman/valijson/blob/master/doc/specifications/draft-zyp-json-schema-03.txt Example of defining self, up, and children link relations within a JSON schema. ```json { "links": [ { "rel": "self" "href": "{id}" }, { "rel": "up" "href": "{upId}" }, { "children": { "rel": "children" "href": "?upId={id}" } } ] } ```