Skip to main content

Crate noson

Crate noson 

Source
Expand description

Generate random JSON values that conform to a JSON Schema.

noson takes a JSON Schema represented as a serde_json::Value and produces a random JSON value that validates against it. The caller supplies the random number generator, making output reproducible when a seeded RNG is used.

§Example

use rand::SeedableRng;
use rand::rngs::StdRng;
use serde_json::json;

let schema = json!({
    "type": "object",
    "properties": {
        "name": { "type": "string", "minLength": 1, "maxLength": 20 },
        "age":  { "type": "integer", "minimum": 0, "maximum": 120 }
    },
    "required": ["name", "age"]
});

let mut rng = StdRng::seed_from_u64(42);
let value = noson::generate(&schema, &mut rng).unwrap();
assert!(value.get("name").unwrap().is_string());
assert!(value.get("age").unwrap().is_i64());

§Supported Schema Features

  • Types: null, boolean, string, integer, number, object, array
  • Constraints: minimum/maximum, exclusiveMinimum/exclusiveMaximum, minLength/maxLength, minItems/maxItems
  • Format: date-time, date, time, duration
  • Enum / Const: enum, const
  • Composition: allOf, anyOf, oneOf
  • References: $ref resolved against $defs / definitions
  • Boolean schemas: true (any value) and false (error)

§Not Supported

The following JSON Schema features are not currently handled. Schemas using them will either be silently ignored (the keyword has no effect on generation) or, in the case of external $ref, return an error.

  • String: pattern, contentEncoding, contentMediaType
  • Numeric: multipleOf
  • Object: additionalProperties, patternProperties, propertyNames, minProperties, maxProperties, unevaluatedProperties
  • Array: prefixItems, additionalItems, contains, minContains, maxContains, uniqueItems, unevaluatedItems
  • Composition: not, if/then/else
  • Dependencies: dependentRequired, dependentSchemas
  • References: external $ref (http/file URIs), $dynamicRef, $anchor
  • Type unions: "type": ["string", "null"] (array form of type)

Enums§

Error
Errors that can occur during JSON value generation.

Functions§

generate
Generate a random JSON value that conforms to the given JSON Schema.