use serde_json::{Map, Value};
const ANNOTATION_KEYWORDS: &[&str] = &[
"$schema",
"$id",
"$comment",
"title",
"description",
"default",
"examples",
"format",
"readOnly",
"writeOnly",
"deprecated",
];
const SUPPORTED_KEYWORDS: &[&str] = &[
"type",
"properties",
"required",
"additionalProperties",
"items",
"enum",
"const",
"minimum",
"maximum",
"exclusiveMinimum",
"exclusiveMaximum",
"minLength",
"maxLength",
"minItems",
"maxItems",
];
pub fn check_supported(schema: &Value) -> Result<(), Vec<String>> {
let mut errors = Vec::new();
check_schema(schema, "", &mut errors);
if errors.is_empty() {
Ok(())
} else {
Err(errors)
}
}
fn check_schema(schema: &Value, pointer: &str, errors: &mut Vec<String>) {
let Some(object) = schema.as_object() else {
if !schema.is_boolean() {
errors.push(format!(
"{}: schema must be an object or boolean",
at(pointer)
));
}
return;
};
for (keyword, value) in object {
if ANNOTATION_KEYWORDS.contains(&keyword.as_str()) {
continue;
}
if !SUPPORTED_KEYWORDS.contains(&keyword.as_str()) {
errors.push(format!(
"{}: unsupported schema keyword '{keyword}'",
at(pointer)
));
continue;
}
match keyword.as_str() {
"properties" => match value.as_object() {
Some(properties) => {
for (name, child) in properties {
check_schema(
child,
&format!("{pointer}/properties/{}", escape(name)),
errors,
);
}
}
None => errors.push(format!("{}: properties must be an object", at(pointer))),
},
"additionalProperties" | "items" => {
check_schema(value, &format!("{pointer}/{keyword}"), errors);
}
"required" => {
if !value
.as_array()
.is_some_and(|names| names.iter().all(Value::is_string))
{
errors.push(format!(
"{}: required must be an array of strings",
at(pointer)
));
}
}
"type" => {
let valid = match value {
Value::String(name) => is_type_name(name),
Value::Array(names) => names
.iter()
.all(|name| name.as_str().is_some_and(is_type_name)),
_ => false,
};
if !valid {
errors.push(format!("{}: type is not a JSON Schema type", at(pointer)));
}
}
"enum" if !value.is_array() => {
errors.push(format!("{}: enum must be an array", at(pointer)));
}
"minimum" | "maximum" | "exclusiveMinimum" | "exclusiveMaximum"
if !value.is_number() =>
{
errors.push(format!("{}: {keyword} must be a number", at(pointer)));
}
"minLength" | "maxLength" | "minItems" | "maxItems" if value.as_u64().is_none() => {
errors.push(format!(
"{}: {keyword} must be a non-negative integer",
at(pointer)
));
}
_ => {}
}
}
}
fn is_type_name(name: &str) -> bool {
matches!(
name,
"null" | "boolean" | "object" | "array" | "number" | "integer" | "string"
)
}
pub fn validate(schema: &Value, value: &Value) -> Result<(), Vec<String>> {
let mut errors = Vec::new();
validate_at(schema, value, "", &mut errors);
if errors.is_empty() {
Ok(())
} else {
Err(errors)
}
}
fn validate_at(schema: &Value, value: &Value, pointer: &str, errors: &mut Vec<String>) {
let object = match schema {
Value::Bool(true) => return,
Value::Bool(false) => {
errors.push(format!("{}: no value is allowed here", at(pointer)));
return;
}
Value::Object(object) => object,
_ => {
errors.push(format!("{}: schema is not an object", at(pointer)));
return;
}
};
for keyword in object.keys() {
if !ANNOTATION_KEYWORDS.contains(&keyword.as_str())
&& !SUPPORTED_KEYWORDS.contains(&keyword.as_str())
{
errors.push(format!(
"{}: unsupported schema keyword '{keyword}'",
at(pointer)
));
}
}
if let Some(types) = object.get("type") {
let allowed: Vec<&str> = match types {
Value::String(name) => vec![name.as_str()],
Value::Array(names) => names.iter().filter_map(Value::as_str).collect(),
_ => Vec::new(),
};
if !allowed.iter().any(|name| has_type(value, name)) {
errors.push(format!(
"{}: expected {}, got {}",
at(pointer),
allowed.join(" or "),
type_of(value)
));
return;
}
}
if let Some(expected) = object.get("const")
&& !json_equal(expected, value)
{
errors.push(format!("{}: must equal {expected}", at(pointer)));
}
if let Some(Value::Array(options)) = object.get("enum")
&& !options.iter().any(|option| json_equal(option, value))
{
errors.push(format!(
"{}: must be one of {}",
at(pointer),
Value::Array(options.clone())
));
}
match value {
Value::Object(fields) => validate_object(object, fields, pointer, errors),
Value::Array(items) => {
if let Some(minimum) = object.get("minItems").and_then(Value::as_u64)
&& (items.len() as u64) < minimum
{
errors.push(format!("{}: needs at least {minimum} items", at(pointer)));
}
if let Some(maximum) = object.get("maxItems").and_then(Value::as_u64)
&& (items.len() as u64) > maximum
{
errors.push(format!("{}: allows at most {maximum} items", at(pointer)));
}
if let Some(item_schema) = object.get("items") {
for (index, item) in items.iter().enumerate() {
validate_at(item_schema, item, &format!("{pointer}/{index}"), errors);
}
}
}
Value::String(text) => {
let length = text.chars().count() as u64;
if let Some(minimum) = object.get("minLength").and_then(Value::as_u64)
&& length < minimum
{
errors.push(format!(
"{}: needs at least {minimum} characters",
at(pointer)
));
}
if let Some(maximum) = object.get("maxLength").and_then(Value::as_u64)
&& length > maximum
{
errors.push(format!(
"{}: allows at most {maximum} characters",
at(pointer)
));
}
}
Value::Number(_) => validate_number(object, value, pointer, errors),
Value::Null | Value::Bool(_) => {}
}
}
fn validate_object(
schema: &Map<String, Value>,
fields: &Map<String, Value>,
pointer: &str,
errors: &mut Vec<String>,
) {
if let Some(Value::Array(required)) = schema.get("required") {
for name in required.iter().filter_map(Value::as_str) {
if !fields.contains_key(name) {
errors.push(format!(
"{}: missing required property '{name}'",
at(pointer)
));
}
}
}
let properties = schema.get("properties").and_then(Value::as_object);
for (name, field) in fields {
let child = format!("{pointer}/{}", escape(name));
match properties.and_then(|properties| properties.get(name)) {
Some(property) => validate_at(property, field, &child, errors),
None => {
if let Some(additional) = schema.get("additionalProperties") {
if additional == &Value::Bool(false) {
errors.push(format!("{}: unknown property '{name}'", at(pointer)));
} else {
validate_at(additional, field, &child, errors);
}
}
}
}
}
}
fn validate_number(
schema: &Map<String, Value>,
value: &Value,
pointer: &str,
errors: &mut Vec<String>,
) {
let checks = [
("minimum", std::cmp::Ordering::Less, false, "at least"),
("maximum", std::cmp::Ordering::Greater, false, "at most"),
(
"exclusiveMinimum",
std::cmp::Ordering::Less,
true,
"greater than",
),
(
"exclusiveMaximum",
std::cmp::Ordering::Greater,
true,
"less than",
),
];
for (keyword, violates, exclusive, wording) in checks {
let Some(bound) = schema.get(keyword) else {
continue;
};
let Some(order) = compare_numbers(value, bound) else {
continue;
};
if order == violates || (exclusive && order == std::cmp::Ordering::Equal) {
errors.push(format!("{}: must be {wording} {bound}", at(pointer)));
}
}
}
fn compare_numbers(left: &Value, right: &Value) -> Option<std::cmp::Ordering> {
if let (Some(left), Some(right)) = (left.as_i64(), right.as_i64()) {
return Some(left.cmp(&right));
}
if let (Some(left), Some(right)) = (left.as_u64(), right.as_u64()) {
return Some(left.cmp(&right));
}
left.as_f64()?.partial_cmp(&right.as_f64()?)
}
fn has_type(value: &Value, name: &str) -> bool {
match name {
"null" => value.is_null(),
"boolean" => value.is_boolean(),
"object" => value.is_object(),
"array" => value.is_array(),
"string" => value.is_string(),
"number" => value.is_number(),
"integer" => {
value.is_i64()
|| value.is_u64()
|| value.as_f64().is_some_and(|number| number.fract() == 0.0)
}
_ => false,
}
}
fn type_of(value: &Value) -> &'static str {
match value {
Value::Null => "null",
Value::Bool(_) => "boolean",
Value::Number(_) => "number",
Value::String(_) => "string",
Value::Array(_) => "array",
Value::Object(_) => "object",
}
}
fn json_equal(left: &Value, right: &Value) -> bool {
match (left, right) {
(Value::Number(_), Value::Number(_)) => {
compare_numbers(left, right) == Some(std::cmp::Ordering::Equal)
}
(Value::Array(left), Value::Array(right)) => {
left.len() == right.len() && left.iter().zip(right).all(|(a, b)| json_equal(a, b))
}
(Value::Object(left), Value::Object(right)) => {
left.len() == right.len()
&& left
.iter()
.all(|(key, a)| right.get(key).is_some_and(|b| json_equal(a, b)))
}
_ => left == right,
}
}
fn at(pointer: &str) -> &str {
if pointer.is_empty() { "input" } else { pointer }
}
fn escape(name: &str) -> String {
name.replace('~', "~0").replace('/', "~1")
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
fn schema() -> Value {
json!({
"type": "object",
"properties": {
"count": {"type": "integer", "minimum": 1, "maximum": 10},
"label": {"type": "string", "minLength": 2, "maxLength": 3},
"mode": {"enum": ["fast", "safe"]},
"tags": {"type": "array", "items": {"type": "string"}, "maxItems": 2},
"note": {"type": ["string", "null"]}
},
"required": ["count"],
"additionalProperties": false
})
}
#[test]
fn accepts_conforming_input() {
let value = json!({"count": 3, "label": "ab", "mode": "safe", "tags": ["x"], "note": null});
assert_eq!(validate(&schema(), &value), Ok(()));
}
#[test]
fn rejects_each_violation_independently() {
let cases = [
json!({}),
json!({"count": 0}),
json!({"count": 11}),
json!({"count": 1.5}),
json!({"count": "1"}),
json!({"count": 1, "label": "a"}),
json!({"count": 1, "label": "abcd"}),
json!({"count": 1, "mode": "slow"}),
json!({"count": 1, "tags": [1]}),
json!({"count": 1, "tags": ["a", "b", "c"]}),
json!({"count": 1, "note": 4}),
json!({"count": 1, "extra": true}),
json!([]),
];
for case in cases {
assert!(validate(&schema(), &case).is_err(), "accepted {case}");
}
}
#[test]
fn counts_unicode_scalars_for_length() {
let schema = json!({"type": "string", "maxLength": 2});
assert_eq!(validate(&schema, &json!("😀😀")), Ok(()));
assert!(validate(&schema, &json!("😀😀😀")).is_err());
}
#[test]
fn compares_large_integers_exactly() {
let schema = json!({"type": "integer", "maximum": 9007199254740993_u64});
assert_eq!(validate(&schema, &json!(9007199254740993_u64)), Ok(()));
assert!(validate(&schema, &json!(9007199254740994_u64)).is_err());
}
#[test]
fn rejects_unsupported_keywords() {
let schema =
json!({"type": "object", "properties": {"a": {"type": "string", "pattern": "x"}}});
assert!(check_supported(&schema).is_err());
assert!(validate(&schema, &json!({"a": "y"})).is_err());
assert_eq!(
check_supported(&json!({"type": "string", "description": "d"})),
Ok(())
);
}
}