jsonfilter 0.2.1

Filter and compare JSON objects
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
mod test;
use std::cmp::Ordering;

use serde_json::json;

/// Compares two JSON values `a` and `b` based on their ordering.
///
/// This function evaluates the relationship between the JSON values `a` and `b` using the following criteria:
/// - If `a` is greater than `b`, returns `std::cmp::Ordering::Greater`.
/// - If `a` is less than `b`, returns `std::cmp::Ordering::Less`.
/// - If `a` is equal to `b`, returns `std::cmp::Ordering::Equal`.
///
/// # Arguments
///
/// * `a` - A reference to a `serde_json::Value` representing the first JSON value.
/// * `b` - A reference to a `serde_json::Value` representing the second JSON value.
///
/// # Returns
///
/// Returns `std::cmp::Ordering` indicating the relationship between `a` and `b`.
///
/// # Panics
///
/// This function panics if the values cant be compared.
///
/// # Examples
///
/// ```
/// use serde_json::json;
/// use std::cmp::Ordering;
/// use jsonfilter::order;
///
/// let a = json!(10);
/// let b = json!(5);
/// assert_eq!(order(&a, &b), Ordering::Greater);
/// ```
#[must_use]
pub fn order(a: &serde_json::Value, b: &serde_json::Value) -> std::cmp::Ordering {
    if matches(
        &serde_json::json!({
            "a": { "$gt": b}
        }),
        &serde_json::json!({
            "a": a
        }),
    ) {
        Ordering::Greater
    } else if matches(
        &serde_json::json!({
            "a": { "$lt": b}
        }),
        &serde_json::json!({
            "a": a
        }),
    ) {
        Ordering::Less
    } else if matches(
        &serde_json::json!({
            "a": b
        }),
        &serde_json::json!({
            "a": a
        }),
    ) {
        Ordering::Equal
    } else {
        unreachable!()
    }
}

/// Compares two `serde_json::Value` objects and determines if the first value is less than the second value.
///
/// # Arguments
///
/// * `a` - A reference to the first `serde_json::Value` to be compared. This can be a floating-point number, integer, unsigned integer, or a string.
/// * `b` - A reference to the second `serde_json::Value` to be compared. This should be of the same type as `a`.
///
/// # Returns
///
/// * `true` if `a` is less than `b`.
/// * `false` otherwise.
///
/// # Panics
///
/// This function will panic if `a` and `b` are not of the same type or if they are of an unsupported type.
fn less_than_json(a: &serde_json::Value, b: &serde_json::Value) -> bool {
    if a.is_f64() {
        let a = a.as_f64().unwrap();
        let b = b.as_f64().unwrap();
        a < b
    } else if a.is_i64() {
        let a = a.as_i64().unwrap();
        let b = b.as_i64().unwrap();
        a < b
    } else if a.is_u64() {
        let a = a.as_u64().unwrap();
        let b = b.as_u64().unwrap();
        a < b
    } else if a.is_string() {
        let a = a.as_str().unwrap();
        let b = b.as_str().unwrap();
        a < b
    } else {
        unreachable!()
    }
}

/// Compares two `serde_json::Value` objects and determines if the first value is greater than the second value.
///
/// # Arguments
///
/// * `a` - A reference to the first `serde_json::Value` to be compared. This can be a floating-point number, integer, unsigned integer, or a string.
/// * `b` - A reference to the second `serde_json::Value` to be compared. This should be of the same type as `a`.
///
/// # Returns
///
/// * `true` if `a` is greater than `b`.
/// * `false` otherwise.
///
/// # Panics
///
/// This function will panic if `a` and `b` are not of the same type or if they are of an unsupported type.
fn greater_than_json(a: &serde_json::Value, b: &serde_json::Value) -> bool {
    if a.is_f64() {
        let a = a.as_f64().unwrap();
        let b = b.as_f64().unwrap();
        a > b
    } else if a.is_i64() {
        let a = a.as_i64().unwrap();
        let b = b.as_i64().unwrap();
        a > b
    } else if a.is_u64() {
        let a = a.as_u64().unwrap();
        let b = b.as_u64().unwrap();
        a > b
    } else if a.is_string() {
        let a = a.as_str().unwrap();
        let b = b.as_str().unwrap();
        a > b
    } else {
        unreachable!()
    }
}

#[derive(Debug, Clone, Copy)]
/// Represents errors that can occur while processing filters.
pub enum FilterError {
    /// Indicates that the schema of the filter is invalid.
    InvalidFilter,
    /// Indicates that an unknown operator was encountered in the filter.
    UnknownOperator,
    /// Indicates that a key was not found in the object being filtered.
    KeyNotFound,
}

/// Matches a filter against a raw object and returns a boolean indicating if the filter matches the object.
///
/// # Arguments
///
/// * `filter` - A reference to a `serde_json::Value` representing the filter to apply. Must be an object.
/// * `obj` - A reference to a `serde_json::Value` representing the object to match against. Must be an object.
///
/// # Returns
///
/// Returns `true` if the filter matches the object, otherwise `false`.
///
/// # Examples
///
/// ```
/// use serde_json::json;
/// use jsonfilter::matches;
///
/// let filter = json!({"name": "John", "age": 30});
/// let obj = json!({"name": "John", "age": 30, "city": "New York"});
///
/// assert!(matches(&filter, &obj));
/// ```
#[must_use]
pub fn matches(filter: &serde_json::Value, obj: &serde_json::Value) -> bool {
    try_matches(filter, obj).unwrap()
}

/// Matches a filter against a raw object and returns a boolean indicating if the filter matches the object.
///
/// # Arguments
///
/// * `filter` - A reference to a `serde_json::Value` representing the filter to apply. Must be an object.
/// * `obj` - A reference to a `serde_json::Value` representing the object to match against. Must be an object.
///
/// # Returns
///
/// * `Ok(true)` if the object matches the filter criteria.
/// * `Ok(false)` if the object does not match the filter criteria.
/// * `Err(FilterError)` if there is an error in the filtering process.
pub fn try_matches(
    filter: &serde_json::Value,
    obj: &serde_json::Value,
) -> Result<bool, FilterError> {
    let filter = filter.as_object().unwrap();
    let obj_map = obj.as_object().unwrap();

    // Handle the case where the filter has a single key, such as top level $and, $or, $not
    if filter.len() == 1 {
        let filter_keys: Vec<_> = filter.keys().collect();
        let op = filter_keys.first().unwrap();
        let op_arg = filter.get(op.as_str()).unwrap();
        match op.as_str() {
            "$and" => {
                if let serde_json::Value::Array(and_list) = op_arg {
                    let and_list_bool: Vec<Result<bool, FilterError>> = and_list
                        .iter()
                        .map(|sub_filter| try_matches(sub_filter, obj))
                        .collect();
                    if let Some(err) = and_list_bool.iter().find(|x| x.is_err()) {
                        return *err;
                    }
                    return Ok(!and_list_bool.iter().map(|x| x.unwrap()).any(|x| !x));
                }
                return Err(FilterError::InvalidFilter);
            }
            "$or" => {
                if let serde_json::Value::Array(or_list) = op_arg {
                    let or_list_bool: Vec<Result<bool, FilterError>> = or_list
                        .iter()
                        .map(|sub_filter| try_matches(sub_filter, obj))
                        .collect();
                    if let Some(err) = or_list_bool.iter().find(|x| x.is_err()) {
                        return *err;
                    }
                    return Ok(or_list_bool.iter().map(|x| x.unwrap()).any(|x| x));
                }
                return Err(FilterError::InvalidFilter);
            }
            "$not" => {
                if let Some(inner) = filter.get("$not") {
                    let new_filter = inner;
                    return Ok(!try_matches(new_filter, obj)?);
                }
                return Err(FilterError::InvalidFilter);
            }
            _ => {
                if op.starts_with('$') {
                    return Err(FilterError::UnknownOperator);
                }
            }
        }
    }

    let mut conditions = vec![];

    for (key, val) in filter {
        if val.is_object() {
            let val_keys: Vec<_> = val.as_object().unwrap().keys().collect();
            if val_keys.first().unwrap().starts_with('$') {
                // handle operators
                conditions.push(match_operator(val, obj, key.as_str()));
            } else {
                // nested
                for (_, _) in val.as_object().unwrap() {
                    let new_filter = filter.get(key).unwrap();
                    if let Some(val) = obj_map.get(key) {
                        conditions.push(try_matches(new_filter, val));
                    } else {
                        return Err(FilterError::KeyNotFound);
                    }
                }
            }
            continue;
        }

        // Compare simple key-value pairs
        if let Some(valb) = obj_map.get(key) {
            if val != valb {
                conditions.push(Ok(false));
            }
        } else {
            return Err(FilterError::KeyNotFound);
        }
    }

    check(&conditions)
}

/// Checks if all conditions in the given list are met.
///
/// This function iterates through a list of `Result<bool, FilterError>` conditions, checking for errors first.
/// If any condition is an error, it returns that error. Otherwise, it returns `Ok(true)` if all conditions are `true`
/// and `Ok(false)` if any condition is `false`.
///
/// # Arguments
///
/// * `conditions` - A slice of `Result<bool, FilterError>` representing the conditions to be checked.
///
/// # Returns
///
/// * `Ok(true)` if all conditions are true.
/// * `Ok(false)` if any condition is false.
/// * `Err(FilterError)` if any condition is an error.
fn check(conditions: &[Result<bool, FilterError>]) -> Result<bool, FilterError> {
    conditions.iter().find(|x| x.is_err()).map_or_else(
        || Ok(!conditions.iter().map(|x| x.unwrap()).any(|x| !x)),
        |possible_error| *possible_error,
    )
}

/// Matches a filter operator against a key-value pair in the object and determines if the condition is met.
///
/// # Arguments
///
/// * `val` - The value associated with the operator in the filter. This should be a JSON object.
/// * `raw_obj` - The object to be filtered. This should be a JSON object.
/// * `key` - The key in the object that the filter operator applies to.
///
/// # Returns
///
/// * `Ok(true)` if the condition specified by the filter operator is met.
/// * `Ok(false)` if the condition specified by the filter operator is not met.
/// * `Err(FilterError)` if there is an error in the filtering process.
///
/// # Errors
///
/// This function will return an error if:
/// * The filter or object is not a valid JSON object.
/// * An unknown operator is used in the filter.
/// * A required key is not found in the object.
/// * The filter format is invalid.
fn match_operator(
    val: &serde_json::Value,
    raw_obj: &serde_json::Value,
    key: &str,
) -> Result<bool, FilterError> {
    let obj = raw_obj.as_object().unwrap();
    let val = val.as_object().unwrap();

    if val.keys().len() == 1 {
        let keys: Vec<_> = val.keys().collect();
        let op = keys.first().unwrap().as_str();
        let op_arg = val.get(op).unwrap();
        match op {
            "$and" => {
                if let serde_json::Value::Array(and_list) = op_arg {
                    let and_list_bool: Vec<Result<bool, FilterError>> = and_list
                        .iter()
                        .map(|sub_filter| try_matches(sub_filter, raw_obj))
                        .collect();
                    if let Some(err) = and_list_bool.iter().find(|x| x.is_err()) {
                        return *err;
                    }
                    return Ok(!and_list_bool.iter().map(|x| x.unwrap()).any(|x| !x));
                }
                return Err(FilterError::InvalidFilter);
            }
            "$or" => {
                if let serde_json::Value::Array(or_list) = op_arg {
                    let or_list_bool: Vec<Result<bool, FilterError>> = or_list
                        .iter()
                        .map(|sub_filter| try_matches(sub_filter, raw_obj))
                        .collect();
                    if let Some(err) = or_list_bool.iter().find(|x| x.is_err()) {
                        return *err;
                    }
                    return Ok(or_list_bool.iter().map(|x| x.unwrap()).any(|x| x));
                }
                return Err(FilterError::InvalidFilter);
            }
            "$lt" => {
                if let Some(a) = obj.get(key) {
                    return Ok(less_than_json(a, op_arg));
                }
                return Err(FilterError::KeyNotFound);
            }
            "$lte" => {
                if let Some(a) = obj.get(key) {
                    return Ok(less_than_json(a, op_arg) || a == op_arg);
                }
                return Err(FilterError::KeyNotFound);
            }
            "$gt" => {
                if let Some(valb) = obj.get(key) {
                    return Ok(greater_than_json(valb, op_arg));
                }
                return Err(FilterError::KeyNotFound);
            }
            "$gte" => {
                if let Some(a) = obj.get(key) {
                    return Ok(greater_than_json(a, op_arg) || a == op_arg);
                }
                return Err(FilterError::KeyNotFound);
            }
            "$not" => {
                if let Some(serde_json::Value::Object(inner)) = val.get("$not") {
                    let new_filter = json!({
                        key: inner
                    });
                    return Ok(!try_matches(&new_filter, raw_obj)?);
                }
                return Err(FilterError::InvalidFilter);
            }
            "$ne" => {
                if let Some(valb) = obj.get(key) {
                    return Ok(valb != op_arg);
                }
                return Err(FilterError::KeyNotFound);
            }
            "$in" => {
                if let Some(valb) = obj.get(key) {
                    if let serde_json::Value::Array(list) = valb {
                        return Ok(list.iter().any(|x| x == op_arg));
                    }
                    return Err(FilterError::InvalidFilter);
                }
                return Err(FilterError::KeyNotFound);
            }
            "$nin" => {
                if let Some(valb) = obj.get(key) {
                    if let serde_json::Value::Array(list) = valb {
                        return Ok(!list.iter().any(|x| x == op_arg));
                    }
                    return Err(FilterError::InvalidFilter);
                }
                return Err(FilterError::KeyNotFound);
            }
            "$exists" => {
                if let serde_json::Value::Bool(exists) = op_arg {
                    let valb = obj.get(key).is_some();
                    return Ok(*exists == valb);
                }
                return Err(FilterError::InvalidFilter);
            }
            "$size" => {
                if let Some(serde_json::Value::Array(list)) = obj.get(key) {
                    let val_size = list.len() as u64;
                    if let serde_json::Value::Number(pref_size) = op_arg {
                        let pref_size = pref_size.as_u64().unwrap();
                        return Ok(pref_size == val_size);
                    }
                    if let serde_json::Value::Object(s_op_obj) = op_arg {
                        if s_op_obj.len() == 1 {
                            let keys: Vec<_> = s_op_obj.keys().collect();
                            let key = keys.first().unwrap();
                            let val = s_op_obj.get(*key).unwrap().as_u64().unwrap();
                            match key.as_str() {
                                "$gt" => {
                                    return Ok(val_size > val);
                                }
                                "$gte" => {
                                    return Ok(val_size >= val);
                                }
                                "$lt" => {
                                    return Ok(val_size < val);
                                }
                                "$lte" => {
                                    return Ok(val_size <= val);
                                }
                                _ => {}
                            }
                        }
                    }
                    return Err(FilterError::InvalidFilter);
                }
                return Err(FilterError::KeyNotFound);
            }
            "$regex" => {
                if let serde_json::Value::String(regex_pattern) = op_arg {
                    if let Some(serde_json::Value::String(valb)) = obj.get(key) {
                        let pattern = regex::Regex::new(regex_pattern).unwrap();
                        return Ok(pattern.is_match(valb));
                    }
                    return Err(FilterError::KeyNotFound);
                }
                return Err(FilterError::InvalidFilter);
            }
            "$type" => {
                if let Some(valb) = obj.get(key) {
                    if let serde_json::Value::String(type_str) = op_arg {
                        return Ok(match type_str.to_lowercase().as_str() {
                            "null" => valb.is_null(),
                            "string" => valb.is_string(),
                            "number" => valb.is_number(),
                            "object" => valb.is_object(),
                            "array" => valb.is_array(),
                            "boolean" => valb.is_boolean(),
                            _ => false,
                        });
                    }
                    return Err(FilterError::InvalidFilter);
                }
                return Err(FilterError::KeyNotFound);
            }
            _ => {
                if op.starts_with('$') {
                    return Err(FilterError::UnknownOperator);
                }
            }
        }
    }

    Err(FilterError::InvalidFilter)
}