pub fn get_from_faststr<Path: IntoIterator>(
json: &FastStr,
path: Path,
) -> Result<LazyValue<'_>>
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.
ยงExamples
// get from the &[&str]
let fs = faststr::FastStr::new(r#"{"a": 1}"#);
let lv = get_from_faststr(&fs, &["a"]).unwrap();
assert_eq!(lv.as_raw_str(), "1");
// not found the field "a"
let lv = get_from_faststr(&fs, &["b"]);
assert!(lv.unwrap_err().is_not_found());
// get from the &[usize]
let fs = faststr::FastStr::new(r#"[0, 1, "two"]"#);
let lv = get_from_faststr(&fs, &[2]).unwrap();
assert_eq!(lv.as_raw_str(), "\"two\"");
// get from pointer!
use sonic_rs::pointer;
let fs = faststr::FastStr::new(r#"{"a": [0, 1, "two"]}"#);
let lv = get_from_faststr(&fs, &pointer!["a", 2]).unwrap();
assert_eq!(lv.as_raw_str(), "\"two\"");
/// the type of JSON is unmatched, expect it is a object
let lv = get_from_faststr(&fs, &pointer!["a", "get key from array"]);
assert!(lv.unwrap_err().is_unmatched_type());