pub fn get_from_str<Path: IntoIterator>(
json: &str,
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 lv = get_from_str(r#"{"a": 1}"#, &["a"]).unwrap();
assert_eq!(lv.as_raw_str(), "1");
// get from the &[usize]
let lv = get_from_str(r#"[0, 1, "two"]"#, &[2]).unwrap();
assert_eq!(lv.as_raw_str(), "\"two\"");
// get from pointer!
use sonic_rs::pointer;
let lv = get_from_str(r#"{"a": [0, 1, "two"]}"#, &pointer!["a", 2]).unwrap();
assert_eq!(lv.as_raw_str(), "\"two\"");
// not found the field "a"
let lv = get_from_str(r#"{"a": 1}"#, &["b"]);
assert!(lv.unwrap_err().is_not_found());
// the type of JSON is unmatched, expect it is a object
let lv = get_from_str(r#"[1, 2, 3]"#, &["b"]);
assert!(lv.unwrap_err().is_unmatched_type());