sonic_rs

Function get

Source
pub fn get<'de, Input, Path: IntoIterator>(
    json: Input,
    path: Path,
) -> Result<LazyValue<'de>>
where Input: JsonInput<'de>, 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.

The input json is allowed to be &FastStr, &[u8], &str, &String or &bytes::Bytes.

§Safety

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

§Examples

use bytes::Bytes;
use faststr::FastStr;
use sonic_rs::get;

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

/// not found the field "a"
let fs = FastStr::new(r#"{"a": 1}"#);
let lv = get(&fs, &["b"]);
assert!(lv.is_err());

/// the JSON is invalid
let b = Bytes::from(r#"{"a": tru }"#);
let lv = get(&b, &["a"]);
assert!(lv.is_err());