Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Type Guards

Runtime type checking and JSON path utilities.

Requires the json feature flag.

Type Guards

is_string

#![allow(unused)]
fn main() {
use rok_utils::types::is_string;
use serde_json::json;

assert!(is_string(&json!("hello")));
assert!(!is_string(&json!(42)));
}

is_number

#![allow(unused)]
fn main() {
use rok_utils::types::is_number;
use serde_json::json;

assert!(is_number(&json!(42)));
assert!(!is_number(&json!("hello")));
}

is_bool

#![allow(unused)]
fn main() {
use rok_utils::types::is_bool;
use serde_json::json;

assert!(is_bool(&json!(true)));
assert!(!is_bool(&json!(42)));
}

is_array

#![allow(unused)]
fn main() {
use rok_utils::types::is_array;
use serde_json::json;

assert!(is_array(&json!([1, 2, 3])));
assert!(!is_array(&json!({"a": 1})));
}

is_object

#![allow(unused)]
fn main() {
use rok_utils::types::is_object;
use serde_json::json;

assert!(is_object(&json!({"a": 1})));
assert!(!is_object(&json!([1, 2, 3])));
}

is_null

#![allow(unused)]
fn main() {
use rok_utils::types::is_null;
use serde_json::json;

assert!(is_null(&json!(null)));
assert!(!is_null(&json!(42)));
}

Path Access

get_path

Access nested values using dot notation:

#![allow(unused)]
fn main() {
use rok_utils::types::get_path;
use serde_json::json;

let data = json!({
    "user": {
        "address": {
            "city": "New York"
        }
    }
});

assert_eq!(get_path(&data, "user.address.city"), Some(&json!("New York")));
assert_eq!(get_path(&data, "user.missing"), None);
}

set_path

Create nested structure and set value:

#![allow(unused)]
fn main() {
use rok_utils::types::set_path;
use serde_json::json;

let data = json!({});
let data = set_path(data, "user.name", json!("Alice"));

assert_eq!(data["user"]["name"], json!("Alice"));
}

Deep Equality

deep_equal

Compare JSON values recursively:

#![allow(unused)]
fn main() {
use rok_utils::types::deep_equal;
use serde_json::json;

assert!(deep_equal(&json!({"a": 1, "b": 2}), &json!({"b": 2, "a": 1})));
assert!(!deep_equal(&json!({"a": 1}), &json!({"a": 2})));
}