Skip to main content

coerce_to_schema

Function coerce_to_schema 

Source
pub fn coerce_to_schema(value: &mut Value, schema: &Value) -> Result<usize>
Expand description

Apply schema-driven type coercions to value in place. Walks the validator output for type-mismatch errors, and for each case where the instance is a Value::String but the schema requires an integer / number / boolean — and the string parses cleanly into that target type — replaces the offending node with the coerced value.

Returns the number of coercions applied. Coercions that don’t have a clean parse (e.g. "abc" against type: integer) are left in place; the caller is expected to re-run validate_against_schema afterwards and surface any remaining violations.

This pairs naturally with hand-written YAML where every value is a string in the typed sense (because the user did not quote vs. unquote intentionally) but the schema knows the intended types. It fits into a CI / formatter pipeline as a “fix pass” before strict validation kicks in.

§Errors

As validate_against_schema.

§Examples

use noyalib::{coerce_to_schema, from_str, Value};

let schema: Value = from_str(
    "type: object\nproperties:\n  port:\n    type: integer\n",
).unwrap();
let mut data: Value = from_str("port: \"8080\"\n").unwrap();
let n = coerce_to_schema(&mut data, &schema).unwrap();
assert_eq!(n, 1, "one fix expected");
// The port is now an integer — re-validation succeeds.
noyalib::validate_against_schema(&data, &schema).unwrap();