pub enum Value<'a> {
Null,
Bool(bool),
Number(Number<'a>),
String(Cow<'a, str>),
Array(Array<'a>),
Object(Object<'a>),
}Expand description
A JSON value, borrowing from the text it was parsed from.
Strings without escape sequences borrow their bytes from the input
(Cow::Borrowed); only a string that had to be unescaped owns a copy.
Numbers keep their exact text (see Number). Object members keep their
document order. The lifetime 'a is the input’s; into_owned
detaches a value from it, and a value built in code from 'static data is
a Value<'static>.
Every operation on a Value (drop, clone, comparison, writing) uses a
bounded amount of stack whatever the depth, so a value of any depth is safe
to use.
Equality is structural and exact: numbers compare by text (1 and 1.0
differ), and object members compare in order. A Value also compares
directly with Rust strings, booleans, and numbers, which is what
assert_eq!(doc["id"], 7) uses.
§Examples
use jsonx_lib::{parse, Value};
let doc = parse(r#"{"user": {"name": "ada", "langs": ["en", "fr"]}, "admin": false}"#)?;
// Index freely: a missing member or item reads as `null`.
assert_eq!(doc["user"]["name"], "ada");
assert_eq!(doc["user"]["langs"][1], "fr");
assert!(doc["nope"][3].is_null());
// Or ask with typed accessors that say whether the shape matched.
assert_eq!(doc["admin"].as_bool(), Some(false));
assert_eq!(doc.pointer("/user/langs/0").and_then(Value::as_str), Some("en"));Variants§
Null
null.
Bool(bool)
true or false.
Number(Number<'a>)
A number, kept as its exact text.
String(Cow<'a, str>)
A string: borrowed from the input when it had no escapes, owned otherwise.
Array(Array<'a>)
An array.
Object(Object<'a>)
An object.
Implementations§
Source§impl<'a> Value<'a>
impl<'a> Value<'a>
Sourcepub const fn kind(&self) -> Kind
pub const fn kind(&self) -> Kind
Which kind of value this is.
§Examples
use jsonx_lib::{json, Kind};
assert_eq!(json!({}).kind(), Kind::Object);Sourcepub const fn as_bool(&self) -> Option<bool>
pub const fn as_bool(&self) -> Option<bool>
The boolean, if the value is one.
§Examples
assert_eq!(jsonx_lib::parse("true")?.as_bool(), Some(true));
assert_eq!(jsonx_lib::parse("1")?.as_bool(), None);Sourcepub const fn as_number(&self) -> Option<&Number<'a>>
pub const fn as_number(&self) -> Option<&Number<'a>>
The number, if the value is one.
§Examples
let doc = jsonx_lib::parse("6.02e23")?;
assert_eq!(doc.as_number().map(|n| n.as_str()), Some("6.02e23"));Sourcepub fn as_i64(&self) -> Option<i64>
pub fn as_i64(&self) -> Option<i64>
The value as an i64: see Number::as_i64. None for anything but
an integer number in range.
§Examples
let doc = jsonx_lib::parse("[-5, 5.5, \"5\"]")?;
assert_eq!(doc[0].as_i64(), Some(-5));
assert_eq!(doc[1].as_i64(), None);
assert_eq!(doc[2].as_i64(), None);Sourcepub fn as_u64(&self) -> Option<u64>
pub fn as_u64(&self) -> Option<u64>
The value as a u64: see Number::as_u64.
§Examples
assert_eq!(jsonx_lib::parse("42")?.as_u64(), Some(42));
assert_eq!(jsonx_lib::parse("-42")?.as_u64(), None);Sourcepub fn as_i128(&self) -> Option<i128>
pub fn as_i128(&self) -> Option<i128>
The value as an i128: see Number::as_i128.
§Examples
let doc = jsonx_lib::parse("-170141183460469231731687303715884105728")?;
assert_eq!(doc.as_i128(), Some(i128::MIN));Sourcepub fn as_u128(&self) -> Option<u128>
pub fn as_u128(&self) -> Option<u128>
The value as a u128: see Number::as_u128.
§Examples
let doc = jsonx_lib::parse("340282366920938463463374607431768211455")?;
assert_eq!(doc.as_u128(), Some(u128::MAX));Sourcepub fn as_f64(&self) -> Option<f64>
pub fn as_f64(&self) -> Option<f64>
The value as an f64: see Number::as_f64. Integers convert too.
§Examples
assert_eq!(jsonx_lib::parse("2")?.as_f64(), Some(2.0));
assert_eq!(jsonx_lib::parse("\"2\"")?.as_f64(), None);Sourcepub fn as_str(&self) -> Option<&str>
pub fn as_str(&self) -> Option<&str>
The string, if the value is one.
§Examples
assert_eq!(jsonx_lib::parse(r#""a\tb""#)?.as_str(), Some("a\tb"));Sourcepub const fn as_array(&self) -> Option<&Array<'a>>
pub const fn as_array(&self) -> Option<&Array<'a>>
The array, if the value is one.
§Examples
let doc = jsonx_lib::parse("[1, 2, 3]")?;
assert_eq!(doc.as_array().map(|a| a.len()), Some(3));Sourcepub fn as_array_mut(&mut self) -> Option<&mut Array<'a>>
pub fn as_array_mut(&mut self) -> Option<&mut Array<'a>>
The array, mutably, if the value is one.
§Examples
let mut v = jsonx_lib::json!([1]);
v.as_array_mut().unwrap().push(2.into());
assert_eq!(v.to_string(), "[1,2]");Sourcepub const fn as_object(&self) -> Option<&Object<'a>>
pub const fn as_object(&self) -> Option<&Object<'a>>
The object, if the value is one.
§Examples
let doc = jsonx_lib::parse(r#"{"k": 1}"#)?;
assert!(doc.as_object().is_some_and(|o| o.contains_key("k")));Sourcepub fn as_object_mut(&mut self) -> Option<&mut Object<'a>>
pub fn as_object_mut(&mut self) -> Option<&mut Object<'a>>
The object, mutably, if the value is one.
§Examples
let mut v = jsonx_lib::json!({});
v.as_object_mut().unwrap().insert("k", "v");
assert_eq!(v.to_string(), r#"{"k":"v"}"#);Sourcepub fn get(&self, key: &str) -> Option<&Value<'a>>
pub fn get(&self, key: &str) -> Option<&Value<'a>>
The value of the member named key, if this is an object that has one.
§Examples
let doc = jsonx_lib::parse(r#"{"jsonrpc": "2.0", "id": 1}"#)?;
assert_eq!(doc.get("jsonrpc").and_then(|v| v.as_str()), Some("2.0"));
assert!(doc.get("method").is_none());Sourcepub fn get_mut(&mut self, key: &str) -> Option<&mut Value<'a>>
pub fn get_mut(&mut self, key: &str) -> Option<&mut Value<'a>>
A mutable reference to the member named key, if this is an object
that has one.
§Examples
let mut v = jsonx_lib::json!({ "n": 1 });
if let Some(n) = v.get_mut("n") {
*n = 2.into();
}
assert_eq!(v["n"], 2);Sourcepub fn get_index(&self, index: usize) -> Option<&Value<'a>>
pub fn get_index(&self, index: usize) -> Option<&Value<'a>>
The item at index, if this is an array that long.
§Examples
let doc = jsonx_lib::parse("[10, 20]")?;
assert_eq!(doc.get_index(1).and_then(|v| v.as_i64()), Some(20));
assert!(doc.get_index(2).is_none());Sourcepub fn pointer(&self, pointer: &str) -> Option<&Value<'a>>
pub fn pointer(&self, pointer: &str) -> Option<&Value<'a>>
Looks a value up by RFC 6901
JSON Pointer: "" is the whole value, /a/0 is item 0 of member a,
and ~1 and ~0 stand for / and ~ inside a key.
Returns None when the pointer is malformed (it does not start with
/, or has a ~ not followed by 0 or 1) or names something that
is not there. An array index must be a plain decimal number without
leading zeros; - (past the end) never resolves.
§Examples
let doc = jsonx_lib::parse(r#"{"a/b": {"c~d": [true]}}"#)?;
assert_eq!(doc.pointer("/a~1b/c~0d/0"), Some(&true.into()));
assert_eq!(doc.pointer(""), Some(&doc));
assert!(doc.pointer("/a~1b/c~0d/01").is_none());
assert!(doc.pointer("a").is_none());Sourcepub fn pointer_mut(&mut self, pointer: &str) -> Option<&mut Value<'a>>
pub fn pointer_mut(&mut self, pointer: &str) -> Option<&mut Value<'a>>
Sourcepub fn take(&mut self) -> Value<'a>
pub fn take(&mut self) -> Value<'a>
Takes the value out, leaving null in its place.
§Examples
let mut v = jsonx_lib::json!({ "big": [1, 2, 3] });
let big = v.get_mut("big").map(|b| b.take()).unwrap_or_default();
assert_eq!(big.to_string(), "[1,2,3]");
assert!(v["big"].is_null());Sourcepub fn into_owned(self) -> Value<'static>
pub fn into_owned(self) -> Value<'static>
Copies every borrowed key, string, and number so the value no longer borrows from the input. Iterative at any depth.
§Examples
use jsonx_lib::{parse, Value};
fn load() -> Result<Value<'static>, jsonx_lib::Error> {
let text = String::from(r#"{"kept": "after the text is gone"}"#);
Ok(parse(&text)?.into_owned())
}
assert_eq!(load()?["kept"], "after the text is gone");Trait Implementations§
impl Eq for Value<'_>
Source§impl From<f64> for Value<'_>
impl From<f64> for Value<'_>
Source§fn from(x: f64) -> Self
fn from(x: f64) -> Self
A number in shortest round-trip form (see Number::from_f64), or
null for NaN and the infinities, which JSON cannot represent.
Source§impl<'a, T: Into<Value<'a>>> FromIterator<T> for Value<'a>
impl<'a, T: Into<Value<'a>>> FromIterator<T> for Value<'a>
Source§fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self
Collects into an array.