json_matcher/
json_matcher.rs

1use serde_json::Value;
2
3use crate::JsonMatcherError;
4
5/// Core trait for implementing JSON value matchers.
6///
7/// Implement this trait to create custom validation logic for JSON values.
8/// The trait requires a single method [`json_matches`](JsonMatcher::json_matches)
9/// that returns a vector of errors - an empty vector indicates a successful match.
10///
11/// # Example
12///
13/// ```
14/// use serde_json::{json, Value};
15/// use json_matcher::{assert_jm, JsonMatcher, JsonMatcherError};
16///
17/// struct OnlyVowels;
18///
19/// impl JsonMatcher for OnlyVowels {
20///     fn json_matches(&self, value: &Value) -> Vec<JsonMatcherError> {
21///         match value.as_str() {
22///             Some(s) if s.chars().all(|c| "aeiouAEIOU".contains(c)) => vec![],
23///             Some(_) => vec![JsonMatcherError::at_root("String contains non-vowel characters")],
24///             None => vec![JsonMatcherError::at_root("Expected string")],
25///         }
26///     }
27/// }
28///
29/// let data = json!({
30///     "sound": "aeiou",
31///     "count": 5
32/// });
33///
34/// assert_jm!(data, {
35///     "sound": OnlyVowels,
36///     "count": 5
37/// });
38/// ```
39pub trait JsonMatcher {
40    fn json_matches(&self, value: &Value) -> Vec<JsonMatcherError>;
41}