sonic_rs::lazyvalue

Function get_from_str_unchecked

Source
pub unsafe fn get_from_str_unchecked<Path: IntoIterator>(
    json: &str,
    path: Path,
) -> Result<LazyValue<'_>>
where Path::Item: Index,
Expand description

Gets a field from a path. And return it as a Result<LazyValue>.

If not found, return an error. If the path is empty, return the whole JSON as a LazyValue.

The Item of the path should implement the Index trait.

§Safety

The JSON must be valid and well-formed, otherwise it may return unexpected result.

§Examples


// get from the &[&str]
let lv = unsafe { get_from_str_unchecked(r#"{"a": 1}"#, &["a"]).unwrap() };
assert_eq!(lv.as_raw_str(), "1");

// get from the &[usize]
let lv = unsafe { get_from_str_unchecked(r#"[0, 1, "two"]"#, &[2]).unwrap() };
assert_eq!(lv.as_raw_str(), "\"two\"");

// get from pointer!
use sonic_rs::pointer;
let lv =
    unsafe { get_from_str_unchecked(r#"{"a": [0, 1, "two"]}"#, &pointer!["a", 2]).unwrap() };
assert_eq!(lv.as_raw_str(), "\"two\"");

// not found the field "a"
let lv = unsafe { get_from_str_unchecked(r#"{"a": 1}"#, &["b"]) };
assert!(lv.unwrap_err().is_not_found());

// the type of JSON is unmatched, expect it is a object
let lv = unsafe { get_from_str_unchecked(r#"[1, 2, 3]"#, &["b"]) };
assert!(lv.unwrap_err().is_unmatched_type());