### JSON Product Example Source: https://docs.ropensci.org/jsonvalidate/articles/jsonvalidate.html A JSON representation of a product with id, name, price, and optional tags. ```json { "id": 1, "name": "A green door", "price": 12.50, "tags": ["home", "green"] } ``` -------------------------------- ### Install jsonvalidate Development Version from GitHub Source: https://docs.ropensci.org/jsonvalidate/index.html Install the latest development version of the jsonvalidate package directly from its GitHub repository using the devtools package. ```R devtools::install_github("ropensci/jsonvalidate") ``` -------------------------------- ### Install jsonvalidate from CRAN Source: https://docs.ropensci.org/jsonvalidate/index.html Install the stable version of the jsonvalidate package from the Comprehensive R Archive Network (CRAN). ```R install.packages("jsonvalidate") ``` -------------------------------- ### Define a Simple JSON Schema Source: https://docs.ropensci.org/jsonvalidate/reference/json_validate.html An example of a JSON schema defining a product with properties like id, name, price, and tags. This schema is used for validation. ```JSON { "$schema": "http://json-schema.org/draft-04/schema#", "title": "Product", "description": "A product from Acme\'s catalog", "type": "object", "properties": { "id": { "description": "The unique identifier for a product", "type": "integer" }, "name": { "description": "Name of the product", "type": "string" }, "price": { "type": "number", "minimum": 0, "exclusiveMinimum": true }, "tags": { "type": "array", "items": { "type": "string" }, "minItems": 1, "uniqueItems": true } }, "required": ["id", "name", "price"] } ``` -------------------------------- ### Validate Correct JSON Source: https://docs.ropensci.org/jsonvalidate/articles/jsonvalidate.html This example shows a JSON object that passes validation against the schema. The `validate` function returns `TRUE` for valid JSON. ```r obj$validate('{ "id": 1, "name": "A green door", "price": 12.50, "tags": ["home", "green"] }') ``` ```r ## [1] TRUE ``` -------------------------------- ### Serialize R object to JSON guided by schema Source: https://docs.ropensci.org/jsonvalidate/reference/json_schema.html Serialize an R object to a JSON string, using the provided schema to guide the unboxing process and ensure correct structure. ```R json_schema$serialise(object) ``` -------------------------------- ### Validate JSON with Negative Price Source: https://docs.ropensci.org/jsonvalidate/articles/jsonvalidate.html This example demonstrates validation failure due to a negative price, which violates the schema's minimum constraint. The `verbose = TRUE` argument returns detailed error information. ```r obj$validate('{ "id": 1, "name": "A green door", "price": -1, "tags": ["home", "green"] }', verbose = TRUE) ``` ```r ## [1] FALSE ## attr(,"errors") ## instancePath schemaPath keyword params.comparison ## 1 /price #/properties/price/minimum minimum > ## params.limit message schema parentSchema.type parentSchema.minimum ## 1 0 must be > 0 0 number 0 ## parentSchema.exclusiveMinimum data dataPath ## 1 TRUE -1 /price ``` -------------------------------- ### Serialize R object to JSON guided by schema Source: https://docs.ropensci.org/jsonvalidate/reference/json_schema.html Serializes an R object into a JSON string, using the schema to guide the unboxing process. This helps ensure the resulting JSON conforms to the schema's structure. ```APIDOC ## Method `serialise()` #### Usage ```R json_schema$serialise(object) ``` #### Arguments `object` An R object to serialise ``` -------------------------------- ### Validate JSON with Multiple Errors Source: https://docs.ropensci.org/jsonvalidate/articles/jsonvalidate.html This example demonstrates a JSON object with several validation errors, including incorrect types for `id` and `name`, a negative `price`, a duplicate tag, and an invalid type within the `tags` array. `verbose = TRUE` is used to capture all errors. ```r obj$validate('{ "id": "identifier", "name": 1, "price": -1, "tags": ["home", "home", 1] }', verbose = TRUE) ``` ```r ## [1] FALSE ## attr(,"errors") ## instancePath schemaPath keyword params.type ## 1 /id #/properties/id/type type integer ## 2 /name #/properties/name/type type string ## 3 /price #/properties/price/minimum minimum ## 4 /tags/2 #/properties/tags/items/type type string ## 5 /tags #/properties/tags/uniqueItems uniqueItems ## params.comparison params.limit params.i params.j ## 1 NA NA NA ## 2 NA NA NA ## 3 > 0 NA NA ## 4 NA NA NA ## 5 NA 0 1 ## message schema ## 1 must be integer integer ## 2 must be string string ## 3 must be > 0 0 ## 4 must be string string ## 5 must NOT have duplicate items (items ## 1 and 0 are identical) TRUE ``` -------------------------------- ### Schema-Guided JSON Serialization with json_serialise Source: https://docs.ropensci.org/jsonvalidate/reference/json_serialise.html Uses jsonvalidate::json_serialise to serialize an R object into JSON, guided by a schema, ensuring correct array structures. ```r jsonvalidate::json_serialise(x, schema) #> {"id":1,"name":"apple","price":0.5,"tags":["fruit"]} ``` -------------------------------- ### Direct JSON Validation Source: https://docs.ropensci.org/jsonvalidate/index.html Use this function to directly validate JSON data against a provided schema. No setup is required beyond loading the package. ```R jsonvalidate::json_validate(json, schema) ``` -------------------------------- ### Validate JSON with Duplicate Tags Source: https://docs.ropensci.org/jsonvalidate/articles/jsonvalidate.html This example shows validation failure caused by duplicate values in the `tags` array, violating the `uniqueItems` constraint. The `verbose = TRUE` argument provides detailed error information. ```r obj$validate('{ "id": 1, "name": "A green door", "price": 12.50, "tags": ["home", "home"] }', verbose = TRUE) ``` ```r ## [1] FALSE ## attr(,"errors") ## instancePath schemaPath keyword params.i params.j ## 1 /tags #/properties/tags/uniqueItems uniqueItems 0 1 ## message schema ## 1 must NOT have duplicate items (items ## 1 and 0 are identical) TRUE ## parentSchema.type parentSchema.type parentSchema.minItems ## 1 array string 1 ## parentSchema.uniqueItems data dataPath ## 1 TRUE home, home /tags ``` -------------------------------- ### json_serialise Source: https://docs.ropensci.org/jsonvalidate/reference/json_serialise.html Safely serialises an R object to a JSON string, using a provided schema to guide the unboxing of scalar values. ```APIDOC ## json_serialise ### Description Safely serialises an R object to a JSON string, using a provided schema to guide the unboxing of scalar values. This function aims to provide a more robust alternative to `jsonlite::toJSON` by ensuring that R types are correctly represented in JSON according to the schema. ### Arguments * **object** (any) - An R object to be serialised. * **schema** (string | path) - A JSON schema, provided as a string or a path to a string, which will be used to validate and guide the serialisation process. * **engine** (string) - The validation engine to use. Currently, only "ajv" is supported. Using other engines will result in an error. * **reference** (string, optional) - A JSON pointer to a sub-schema within the main schema. This allows validation against a specific part of the schema, for example, a definition within a larger schema. * **strict** (boolean) - If TRUE, the schema will be parsed strictly, leading to errors for unknown formats or keywords. Defaults to FALSE. This option is only available when `engine = "ajv"`. ### Value A string representing the input `object` in JSON format. The output string is assigned a `"json"` class attribute, similar to `jsonlite::toJSON`. ### Details This function addresses discrepancies between R's data types and JSON's types, particularly concerning scalar values. Unlike `jsonlite::toJSON`, which might automatically unbox or require explicit `unbox()` calls, `json_serialise` uses the provided schema to determine if a length-1 R vector should be serialised as a JSON scalar or a JSON array. The process involves serialising the object with `jsonlite::toJSON` (with `auto_unbox = FALSE`), then using JavaScript to parse, unbox based on the schema, and re-serialise the object. ### Warning Directly using `json_serialise` can be slow for multiple serialisations. For better performance when serialising multiple objects with the same schema, it is recommended to use the `serialise` method of a pre-created `json_schema` object. ### Examples ```R # Define a JSON schema schema <- '{ "$schema": "http://json-schema.org/draft-04/schema#", "title": "Product", "description": "A product from Acme\'s catalog", "type": "object", "properties": { "id": { "description": "The unique identifier for a product", "type": "integer" }, "name": { "description": "Name of the product", "type": "string" }, "price": { "type": "number", "minimum": 0, "exclusiveMinimum": true }, "tags": { "type": "array", "items": { "type": "string" }, "minItems": 1, "uniqueItems": true } }, "required": ["id", "name", "price"] }' # Create a validator object using the schema v <- jsonvalidate::json_validator(schema, engine = "ajv") # R object to serialise x <- list(id = 1, name = "apple", price = 0.50, tags = "fruit") # Serialise the object using the schema json_output <- json_serialise(object = x, schema = schema) print(json_output) ``` ``` -------------------------------- ### JSON serialization with and without schema guidance Source: https://docs.ropensci.org/jsonvalidate/reference/json_schema.html Demonstrates how jsonlite::toJSON behaves with and without schema guidance, highlighting potential validation failures. It shows the default behavior, auto-unboxing, and the correct serialization using jsonvalidate::json_serialise. ```R # We're going to use a validator object below v <- jsonvalidate::json_validator(schema, "ajv") # And this is some data that we might generate in R that we want to # serialise using that schema x <- list(id = 1, name = "apple", price = 0.50, tags = "fruit") # If we serialise to json, then 'id', 'name' and "price' end up a # length 1-arrays jsonlite::toJSON(x) #> {"id":[1],"name":["apple"],"price":[0.5],"tags":["fruit"]} # ...and that fails validation v(jsonlite::toJSON(x)) #> [1] FALSE # If we auto-unbox then 'fruit' ends up as a string and not an array, # also failing validation: jsonlite::toJSON(x, auto_unbox = TRUE) #> {"id":1,"name":"apple","price":0.5,"tags":"fruit"} v(jsonlite::toJSON(x, auto_unbox = TRUE)) #> [1] FALSE # Using json_serialise we can guide the serialisation process using # the schema: jsonvalidate::json_serialise(x, schema) #> {"id":1,"name":"apple","price":0.5,"tags":["fruit"]} ``` -------------------------------- ### Basic JSON Serialization with jsonlite Source: https://docs.ropensci.org/jsonvalidate/reference/json_serialise.html Demonstrates default JSON serialization using jsonlite::toJSON. This output may not pass schema validation if arrays are expected. ```r jsonlite::toJSON(x) #> {"id":[1],"name":["apple"],"price":[0.5],"tags":["fruit"]} ``` -------------------------------- ### JSON Schema for Product Source: https://docs.ropensci.org/jsonvalidate/articles/jsonvalidate.html A JSON schema defining the structure and constraints for a product object. ```json { "$schema": "http://json-schema.org/draft-04/schema#", "title": "Product", "description": "A product from Acme's catalog", "type": "object", "properties": { "id": { "description": "The unique identifier for a product", "type": "integer" }, "name": { "description": "Name of the product", "type": "string" }, "price": { "type": "number", "minimum": 0, "exclusiveMinimum": true }, "tags": { "type": "array", "items": { "type": "string" }, "minItems": 1, "uniqueItems": true } }, "required": ["id", "name", "price"] } ``` -------------------------------- ### Combine Schemas with Definitions using ajv Source: https://docs.ropensci.org/jsonvalidate/articles/jsonvalidate.html Combine schemas by referencing definitions within the same schema file using the 'ajv' engine. Ensure the schema is correctly structured with a 'definitions' block. ```R schema <- '{ "$schema": "http://json-schema.org/draft-04/schema#", "definitions": { "city": { "type": "string" } }, "type": "object", "properties": { "city": { "$ref": "#/definitions/city" } } }' json <- '{ "city": "Firenze" }' jsonvalidate::json_validate(json, schema, engine = "ajv") ``` -------------------------------- ### Create a json_schema object Source: https://docs.ropensci.org/jsonvalidate/reference/json_schema.html Instantiate a json_schema object with a schema definition and optionally specify the validation engine, a reference within the schema, and strict parsing mode. ```R json_schema$new(schema, engine = "ajv", reference = NULL, strict = FALSE) ``` -------------------------------- ### Reference Schema in Subdirectory with ajv Source: https://docs.ropensci.org/jsonvalidate/articles/jsonvalidate.html Combine schemas located in subdirectories by using relative paths in '$ref'. Absolute paths are not supported and will cause an error. ```R user_schema = '{ "$schema": "http://json-schema.org/draft-07/schema", "type": "object", "required": ["address"], "properties": { "address": { "$ref": "sub/address.json" } } }' json <- '{ "address": { "city": "Firenze" } }' path <- tempfile() subdir <- file.path(path, "sub") dir.create(subdir, showWarnings = FALSE, recursive = TRUE) city_path <- file.path(subdir, "city.json") address_path <- file.path(subdir, "address.json") user_path <- file.path(path, "schema.json") writeLines(city_schema, city_path) writeLines(address_schema, address_path) writeLines(user_schema, user_path) jsonvalidate::json_validate(json, user_path, engine = "ajv") ``` -------------------------------- ### Create a new json_schema object Source: https://docs.ropensci.org/jsonvalidate/reference/json_schema.html Initializes a new `json_schema` object with a specified schema and validation engine. It supports options for referencing sub-schemas and strict parsing. ```APIDOC ## Method `new()` Create a new `json_schema` object. ### Usage ```R json_schema$new(schema, engine = "ajv", reference = NULL, strict = FALSE) ``` ### Arguments `schema` Contents of the json schema, or a filename containing a schema. `engine` Specify the validation engine to use. Options are "ajv" (the default; "Another JSON Schema Validator") or "imjv" ("is-my-json-valid", the default everywhere in versions prior to 1.4.0, and the default for json_validator. _Use of`ajv` is strongly recommended for all new code_. `reference` Reference within schema to use for validating against a sub-schema instead of the full schema passed in. For example if the schema has a 'definitions' list including a definition for a 'Hello' object, one could pass "#/definitions/Hello" and the validator would check that the json is a valid "Hello" object. Only available if `engine = "ajv"`. `strict` Set whether the schema should be parsed strictly or not. If in strict mode schemas will error to "prevent any unexpected behaviours or silently ignored mistakes in user schema". For example it will error if encounters unknown formats or unknown keywords. See https://ajv.js.org/strict-mode.html for details. Only available in `engine = "ajv"` and silently ignored for "imjv". Validate a json string against a schema. ``` -------------------------------- ### R Object for Serialization Source: https://docs.ropensci.org/jsonvalidate/reference/json_serialise.html An R list representing product data that will be serialized into a JSON string according to the provided schema. Note the 'tags' element is a single string, which json_serialise can handle correctly based on the schema. ```R x <- list(id = 1, name = "apple", price = 0.50, tags = "fruit") ``` -------------------------------- ### Reference External Schema File with ajv Source: https://docs.ropensci.org/jsonvalidate/articles/jsonvalidate.html Reference a schema from another file using '$ref' with the 'ajv' engine. The referenced file path should be correct relative to the main schema file. ```R city_schema <- '{ "$schema": "http://json-schema.org/draft-07/schema", "type": "string", "enum": ["Firenze"] }' address_schema <- '{ "$schema": "http://json-schema.org/draft-07/schema", "type":"object", "properties": { "city": { "$ref": "city.json" } } }' path <- tempfile() dir.create(path) address_path <- file.path(path, "address.json") city_path <- file.path(path, "city.json") writeLines(address_schema, address_path) writeLines(city_schema, city_path) jsonvalidate::json_validate(json, address_path, engine = "ajv") ``` -------------------------------- ### Efficient JSON Schema Construction and Validation Source: https://docs.ropensci.org/jsonvalidate/reference/json_schema.html Constructs a JSON schema object first for more efficient serialization and validation operations. This is typically faster than repeated direct calls. ```r obj <- jsonvalidate::json_schema$new(schema) json <- obj$serialise(x) obj$validate(json) #> [1] TRUE ``` -------------------------------- ### JSON Serialization with jsonlite and auto_unbox Source: https://docs.ropensci.org/jsonvalidate/reference/json_serialise.html Illustrates JSON serialization using jsonlite::toJSON with auto_unbox = TRUE. This can cause single-element arrays to become strings, potentially failing validation. ```r jsonlite::toJSON(x, auto_unbox = TRUE) #> {"id":1,"name":"apple","price":0.5,"tags":"fruit"} ``` -------------------------------- ### Create JSON Schema Object from File in R Source: https://docs.ropensci.org/jsonvalidate/articles/jsonvalidate.html Create a JSON schema validation object by loading the schema from a file path. This is useful for large schemas. ```r path <- tempfile() writeLines(schema, path) obj <- jsonvalidate::json_schema$new(path) ``` -------------------------------- ### Validate JSON String Against Schema (Basic) Source: https://docs.ropensci.org/jsonvalidate/articles/jsonvalidate.html Validate an empty JSON string against a pre-defined schema object. Returns FALSE if validation fails. ```r obj$validate("{}") ``` -------------------------------- ### json_serialise Function Signature Source: https://docs.ropensci.org/jsonvalidate/reference/json_serialise.html Defines the arguments for the json_serialise function, including the object to serialize, the schema, and optional engine, reference, and strictness parameters. ```R json_serialise( object, schema, engine = "ajv", reference = NULL, strict = FALSE ) ``` -------------------------------- ### Validate a JSON fraction against a schema reference Source: https://docs.ropensci.org/jsonvalidate/reference/json_validate.html Validates a specific part of the JSON data ('tags') against a corresponding reference within the schema, using the 'ajv' engine and verbose output. ```R jsonvalidate::json_validate(json, schema, query = "tags", reference = "#/properties/tags", engine = "ajv", verbose = TRUE) #> [1] TRUE ``` -------------------------------- ### Validate Invalid JSON against Schema Source: https://docs.ropensci.org/jsonvalidate/reference/json_validate.html Tests an empty JSON object against the defined schema, demonstrating how validation failures are reported when verbose is TRUE. ```R jsonvalidate::json_validate("{}", schema, verbose = TRUE) #> [1] FALSE #> attr(,"errors") #> field message #> 1 data.id is required #> 2 data.name is required #> 3 data.price is required ``` -------------------------------- ### Create Validator with ajv Engine Source: https://docs.ropensci.org/jsonvalidate/reference/json_validator.html Uses the 'ajv' engine for JSON schema validation, required for draft-06 or draft-07 features. The schema is defined as a string. ```R schema <- "{ '$schema': 'http://json-schema.org/draft-06/schema#', 'type': 'object', 'properties': { 'a': { 'const': 'foo' } } }" # Create the validator v <- jsonvalidate::json_validator(schema, engine = "ajv") ``` -------------------------------- ### Validate Valid JSON against Schema Source: https://docs.ropensci.org/jsonvalidate/reference/json_validate.html Tests a valid JSON object against the defined schema to confirm successful validation. ```R json <- '{ "id": 1, "name": "A green door", "price": 12.50, "tags": ["home", "green"] }' jsonvalidate::json_validate(json, schema) #> [1] TRUE ``` -------------------------------- ### Create Reusable JSON Validator Source: https://docs.ropensci.org/jsonvalidate/index.html Create a validator object from a schema for efficient validation of multiple JSON objects. This is useful when validating many JSON documents against the same schema. ```R validate <- jsonvalidate::json_validator(schema) validate(json) validate(json2) # etc ``` -------------------------------- ### Validate JSON String Against Schema (Verbose) Source: https://docs.ropensci.org/jsonvalidate/articles/jsonvalidate.html Validate an empty JSON string against a schema object and retrieve detailed error information by setting verbose = TRUE. ```r obj$validate("{}", verbose = TRUE) ``` -------------------------------- ### Create Reusable Validator with ajv Source: https://docs.ropensci.org/jsonvalidate/articles/jsonvalidate.html Create a reusable validator object using json_validator for repeated validations. This is more efficient than direct validation for multiple checks. ```R v <- jsonvalidate::json_validator(schema, engine = "ajv") v(json) ``` -------------------------------- ### Validate JSON conforming to schema Source: https://docs.ropensci.org/jsonvalidate/reference/json_validator.html Validates a JSON object against a schema created with the 'ajv' engine. Returns TRUE if it conforms. ```R v('{"a": "foo"}') #> [1] TRUE ``` -------------------------------- ### Validation Failure with Default jsonlite Serialization Source: https://docs.ropensci.org/jsonvalidate/reference/json_serialise.html Shows that the default JSON output from jsonlite::toJSON fails validation against a schema that expects specific array structures. ```r v(jsonlite::toJSON(x)) #> [1] FALSE ``` -------------------------------- ### Validation Failure with auto_unbox in jsonlite Source: https://docs.ropensci.org/jsonvalidate/reference/json_serialise.html Demonstrates that using auto_unbox = TRUE in jsonlite::toJSON can lead to validation failures if the schema expects arrays. ```r v(jsonlite::toJSON(x, auto_unbox = TRUE)) #> [1] FALSE ``` -------------------------------- ### Define JSON Schema as String in R Source: https://docs.ropensci.org/jsonvalidate/articles/jsonvalidate.html Define a JSON schema as a string variable in R. Ensure proper escaping of quotes within the JSON string. ```r schema <- '{ "$schema": "http://json-schema.org/draft-04/schema#", "title": "Product", "description": "A product from Acme\'s catalog", "type": "object", "properties": { "id": { "description": "The unique identifier for a product", "type": "integer" }, "name": { "description": "Name of the product", "type": "string" }, "price": { "type": "number", "minimum": 0, "exclusiveMinimum": true }, "tags": { "type": "array", "items": { "type": "string" }, "minItems": 1, "uniqueItems": true } }, "required": ["id", "name", "price"] }' ``` -------------------------------- ### Create a JSON Validator Function Source: https://docs.ropensci.org/jsonvalidate/reference/json_validator.html Use `json_validator` to create a function that validates JSON data against a specified schema. The default engine is 'imjv', but 'ajv' offers more features. The returned function has 'v8' and 'engine' attributes. ```R schema <- '{ "$schema": "http://json-schema.org/draft-04/schema#", "title": "Product", "description": "A product from Acme\'s catalog", "type": "object", "properties": { "id": { "description": "The unique identifier for a product", "type": "integer" }, "name": { "description": "Name of the product", "type": "string" }, "price": { "type": "number", "minimum": 0, "exclusiveMinimum": true }, "tags": { "type": "array", "items": { "type": "string" }, "minItems": 1, "uniqueItems": true } }, "required": ["id", "name", "price"] }' # Create a validator function v <- jsonvalidate::json_validator(schema) ``` -------------------------------- ### Direct JSON Validation with ajv Source: https://docs.ropensci.org/jsonvalidate/articles/jsonvalidate.html Use json_validate for a quick validation of JSON data against a schema using the 'ajv' engine. This is suitable for single validations. ```R json <- '{ "id": 1, "name": "A green door", "price": 12.50, "tags": ["home", "green"] }' schema <- '{...}' # Assume schema is defined jsonvalidate::json_validate(json, schema, engine = "ajv") ``` -------------------------------- ### Validate Valid JSON Source: https://docs.ropensci.org/jsonvalidate/reference/json_validator.html Test if valid JSON conforms to the schema. Returns TRUE if the JSON is valid. ```R v('{ "id": 1, "name": "A green door", "price": 12.50, "tags": ["home", "green"] }') #> [1] TRUE ``` -------------------------------- ### Validate JSON with Schema Source: https://docs.ropensci.org/jsonvalidate/reference/json_schema.html Passes validation when the JSON data conforms to the provided schema. ```r v(jsonvalidate::json_serialise(x, schema)) #> [1] TRUE ``` -------------------------------- ### Validate JSON against a schema Source: https://docs.ropensci.org/jsonvalidate/reference/json_schema.html Validate a JSON object or string against the schema associated with the json_schema object. Options include verbose output, greedy error checking, and throwing errors on failure. ```R json_schema$validate( json, verbose = FALSE, greedy = FALSE, error = FALSE, query = NULL ) ``` -------------------------------- ### Throw Error on Validation Failure Source: https://docs.ropensci.org/jsonvalidate/articles/jsonvalidate.html Use `error = TRUE` to make the `validate` function throw an error when JSON validation fails. This is useful for stopping execution immediately upon encountering invalid data. ```r obj$validate("{}", error = TRUE) ``` -------------------------------- ### Validate JSON not conforming to schema Source: https://docs.ropensci.org/jsonvalidate/reference/json_validator.html Validates a JSON object against a schema created with the 'ajv' engine. Returns FALSE if it does not conform. ```R v('{"a": "bar"}') #> [1] FALSE ``` -------------------------------- ### json_validate Function Signature Source: https://docs.ropensci.org/jsonvalidate/reference/json_validate.html Defines the parameters for the json_validate function, including json data, schema, and various validation options. ```R json_validate( json, schema, verbose = FALSE, greedy = FALSE, error = FALSE, engine = "imjv", reference = NULL, query = NULL, strict = FALSE ) ``` -------------------------------- ### Create JSON Schema Object from String in R Source: https://docs.ropensci.org/jsonvalidate/articles/jsonvalidate.html Create a JSON schema validation object from a JSON schema string using jsonvalidate::json_schema$new(). ```r obj <- jsonvalidate::json_schema$new(schema) ``` -------------------------------- ### Validate JSON data against a schema Source: https://docs.ropensci.org/jsonvalidate/reference/json_schema.html Validates a JSON string or file against the `json_schema` object. Supports verbose output, greedy validation, error throwing, and querying specific components of the JSON data. ```APIDOC ## Method `validate()` #### Usage ```R json_schema$validate( json, verbose = FALSE, greedy = FALSE, error = FALSE, query = NULL ) ``` #### Arguments `json` Contents of a json object, or a filename containing one. `verbose` Be verbose? If `TRUE`, then an attribute "errors" will list validation failures as a data.frame `greedy` Continue after the first error? `error` Throw an error on parse failure? If `TRUE`, then the function returns `NULL` on success (i.e., call only for the side-effect of an error on failure, like `stopifnot`). `query` A string indicating a component of the data to validate the schema against. Eventually this may support full jsonpath syntax, but for now this must be the name of an element within `json`. See the examples for more details. Serialise an R object to JSON with unboxing guided by the schema. See json_serialise for details on the problem and the algorithm. ``` -------------------------------- ### Display Validation Errors Source: https://docs.ropensci.org/jsonvalidate/articles/jsonvalidate.html When validation fails without `error = TRUE`, the `errors` attribute of the returned value contains a data.frame with detailed error messages from `ajv`. This is helpful for debugging and understanding why validation failed. ```r ## Error: ## ! 3 errors validating json: ## - (#/required): must have required property 'id' ## - (#/required): must have required property 'name' ## - (#/required): must have required property 'price' ``` -------------------------------- ### Validate Invalid JSON Source: https://docs.ropensci.org/jsonvalidate/reference/json_validator.html Test if invalid JSON conforms to the schema. When verbose is TRUE, it returns FALSE and lists the validation errors. ```R v("{}", verbose = TRUE) #> [1] FALSE #> attr(,"errors") #> field message #> 1 data.id is required #> 2 data.name is required #> 3 data.price is required ``` -------------------------------- ### json_validator Function Source: https://docs.ropensci.org/jsonvalidate/reference/json_validator.html Creates a validator function that can be used to validate JSON data against a specified schema. It supports different validation engines and options for strict parsing. ```APIDOC ## json_validator ### Description Create a validator that can validate multiple json files. ### Usage ```R json_validator(schema, engine = "imjv", reference = NULL, strict = FALSE) ``` ### Arguments * **schema** (string or filename) - Contents of the json schema, or a filename containing a schema. * **engine** (string) - Specify the validation engine to use. Options are "imjv" (default) and "ajv". * **reference** (string, optional) - Reference within schema to use for validating against a sub-schema. Only available if `engine = "ajv"`. * **strict** (boolean) - Set whether the schema should be parsed strictly or not. Only available in `engine = "ajv"`. ### Value A function that can be used to validate a schema. Additionally, the function has two attributes assigned: `v8` which is the JavaScript context (used internally) and `engine`, which contains the name of the engine used. ### Examples ```R # A simple schema example: schema <- '{ "$schema": "http://json-schema.org/draft-04/schema#", "title": "Product", "description": "A product from Acme\'s catalog", "type": "object", "properties": { "id": { "description": "The unique identifier for a product", "type": "integer" }, "name": { "description": "Name of the product", "type": "string" }, "price": { "type": "number", "minimum": 0, "exclusiveMinimum": true }, "tags": { "type": "array", "items": { "type": "string" }, "minItems": 1, "uniqueItems": true } }, "required": ["id", "name", "price"] }' # Create a validator function v <- jsonvalidate::json_validator(schema) ``` ``` -------------------------------- ### json_validate Function Source: https://docs.ropensci.org/jsonvalidate/reference/json_validate.html Validates a single JSON object against a schema. This function is a wrapper around more detailed validation mechanisms. ```APIDOC ## json_validate ### Description Validate a single json against a schema. This is a convenience wrapper around `json_validator(schema)(json)` or `json_schema$new(schema, engine = "ajv")$validate(json)`. See `json_validator()` for further details. ### Usage ```R json_validate( json, schema, verbose = FALSE, greedy = FALSE, error = FALSE, engine = "imjv", reference = NULL, query = NULL, strict = FALSE ) ``` ### Arguments * `json` (any) - Contents of a json object, or a filename containing one. * `schema` (any) - Contents of the json schema, or a filename containing a schema. * `verbose` (logical) - Be verbose? If `TRUE`, then an attribute "errors" will list validation failures as a data.frame. Defaults to `FALSE`. * `greedy` (logical) - Continue after the first error? Defaults to `FALSE`. * `error` (logical) - Throw an error on parse failure? If `TRUE`, then the function returns `NULL` on success (i.e., call only for the side-effect of an error on failure, like `stopifnot`). Defaults to `FALSE`. * `engine` (character) - Specify the validation engine to use. Options are "imjv" (the default; which uses "is-my-json-valid") and "ajv" (Another JSON Schema Validator). The latter supports more recent json schema features. Defaults to "imjv". * `reference` (character) - Reference within schema to use for validating against a sub-schema instead of the full schema passed in. For example if the schema has a 'definitions' list including a definition for a 'Hello' object, one could pass "#/definitions/Hello" and the validator would check that the json is a valid "Hello" object. Only available if `engine = "ajv"`. Defaults to `NULL`. * `query` (character) - A string indicating a component of the data to validate the schema against. Eventually this may support full jsonpath syntax, but for now this must be the name of an element within `json`. See the examples for more details. Defaults to `NULL`. * `strict` (logical) - Set whether the schema should be parsed strictly or not. If in strict mode schemas will error to "prevent any unexpected behaviours or silently ignored mistakes in user schema". For example it will error if encounters unknown formats or unknown keywords. See https://ajv.js.org/strict-mode.html for details. Only available in `engine = "ajv"`. Defaults to `FALSE`. ### Examples ```R # A simple schema example: schema <- '{ "$schema": "http://json-schema.org/draft-04/schema#", "title": "Product", "description": "A product from Acme\'s catalog", "type": "object", "properties": { "id": { "description": "The unique identifier for a product", "type": "integer" }, "name": { "description": "Name of the product", "type": "string" }, "price": { "type": "number", "minimum": 0, "exclusiveMinimum": true }, "tags": { "type": "array", "items": { "type": "string" }, "minItems": 1, "uniqueItems": true } }, "required": ["id", "name", "price"] }' # Test if some (invalid) json conforms to the schema jsonvalidate::json_validate("{}", schema, verbose = TRUE) #> [1] FALSE #> attr(,"errors") #> field message #> 1 data.id is required #> 2 data.name is required #> 3 data.price is required # Test if some (valid) json conforms to the schema json <- '{ "id": 1, "name": "A green door", "price": 12.50, "tags": ["home", "green"] }' jsonvalidate::json_validate(json, schema) #> [1] TRUE # Test a fraction of a data against a reference into the schema: jsonvalidate::json_validate(json, schema, query = "tags", reference = "#/properties/tags", engine = "ajv", verbose = TRUE) #> [1] TRUE ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.