Skip to main content

Value

Enum Value 

Source
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>

Source

pub const fn kind(&self) -> Kind

Which kind of value this is.

§Examples
use jsonx_lib::{json, Kind};

assert_eq!(json!({}).kind(), Kind::Object);
Source

pub const fn is_null(&self) -> bool

Whether the value is null.

§Examples
assert!(jsonx_lib::parse("null")?.is_null());
Source

pub const fn is_bool(&self) -> bool

Whether the value is true or false.

§Examples
assert!(jsonx_lib::json!(false).is_bool());
Source

pub const fn is_number(&self) -> bool

Whether the value is a number.

§Examples
assert!(jsonx_lib::json!(1.5).is_number());
Source

pub const fn is_string(&self) -> bool

Whether the value is a string.

§Examples
assert!(jsonx_lib::json!("s").is_string());
Source

pub const fn is_array(&self) -> bool

Whether the value is an array.

§Examples
assert!(jsonx_lib::json!([]).is_array());
Source

pub const fn is_object(&self) -> bool

Whether the value is an object.

§Examples
assert!(jsonx_lib::json!({}).is_object());
Source

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);
Source

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"));
Source

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);
Source

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);
Source

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));
Source

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));
Source

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);
Source

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"));
Source

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));
Source

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]");
Source

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")));
Source

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"}"#);
Source

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());
Source

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);
Source

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());
Source

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());
Source

pub fn pointer_mut(&mut self, pointer: &str) -> Option<&mut Value<'a>>

A mutable reference to the value at a JSON Pointer, as pointer finds it.

§Examples
let mut v = jsonx_lib::json!({ "a": [1, 2] });
if let Some(item) = v.pointer_mut("/a/1") {
    *item = "two".into();
}
assert_eq!(v.to_string(), r#"{"a":[1,"two"]}"#);
assert!(v.pointer_mut("/a/9").is_none());
Source

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());
Source

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§

Source§

impl Clone for Value<'_>

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Value<'_>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Writes the value as compact JSON.

Source§

impl<'a> Default for Value<'a>

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl Display for Value<'_>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Writes the value as compact JSON, or as indented JSON with the alternate flag ({:#}).

§Examples
let v = jsonx_lib::json!({ "a": [1] });
assert_eq!(format!("{v}"), r#"{"a":[1]}"#);
assert_eq!(format!("{v:#}"), "{\n  \"a\": [\n    1\n  ]\n}");
Source§

impl Eq for Value<'_>

Source§

impl<'a> From<&'a String> for Value<'a>

Source§

fn from(s: &'a String) -> Self

Converts to this type from the input type.
Source§

impl<'a> From<&'a str> for Value<'a>

Source§

fn from(s: &'a str) -> Self

Converts to this type from the input type.
Source§

impl From<()> for Value<'_>

Source§

fn from((): ()) -> Self

() is null.

Source§

impl<'a> From<Array<'a>> for Value<'a>

Source§

fn from(a: Array<'a>) -> Self

Converts to this type from the input type.
Source§

impl<'a> From<Cow<'a, str>> for Value<'a>

Source§

fn from(s: Cow<'a, str>) -> Self

Converts to this type from the input type.
Source§

impl<'a> From<Number<'a>> for Value<'a>

Source§

fn from(n: Number<'a>) -> Self

Converts to this type from the input type.
Source§

impl<'a> From<Object<'a>> for Value<'a>

Source§

fn from(o: Object<'a>) -> Self

Converts to this type from the input type.
Source§

impl<'a, T: Into<Value<'a>>> From<Option<T>> for Value<'a>

Source§

fn from(value: Option<T>) -> Self

None is null.

Source§

impl From<String> for Value<'_>

Source§

fn from(s: String) -> Self

Converts to this type from the input type.
Source§

impl<'a, T: Into<Value<'a>>> From<Vec<T>> for Value<'a>

Source§

fn from(items: Vec<T>) -> Self

Converts to this type from the input type.
Source§

impl From<bool> for Value<'_>

Source§

fn from(b: bool) -> Self

Converts to this type from the input type.
Source§

impl From<char> for Value<'_>

Source§

fn from(c: char) -> Self

Converts to this type from the input type.
Source§

impl From<f32> for Value<'_>

Source§

fn from(x: f32) -> Self

The f32 widened to f64 (exactly), then as From<f64>.

Source§

impl From<f64> for Value<'_>

Source§

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 From<i8> for Value<'_>

Source§

fn from(n: i8) -> Self

Converts to this type from the input type.
Source§

impl From<i16> for Value<'_>

Source§

fn from(n: i16) -> Self

Converts to this type from the input type.
Source§

impl From<i32> for Value<'_>

Source§

fn from(n: i32) -> Self

Converts to this type from the input type.
Source§

impl From<i64> for Value<'_>

Source§

fn from(n: i64) -> Self

Converts to this type from the input type.
Source§

impl From<i128> for Value<'_>

Source§

fn from(n: i128) -> Self

Converts to this type from the input type.
Source§

impl From<isize> for Value<'_>

Source§

fn from(n: isize) -> Self

Converts to this type from the input type.
Source§

impl From<u8> for Value<'_>

Source§

fn from(n: u8) -> Self

Converts to this type from the input type.
Source§

impl From<u16> for Value<'_>

Source§

fn from(n: u16) -> Self

Converts to this type from the input type.
Source§

impl From<u32> for Value<'_>

Source§

fn from(n: u32) -> Self

Converts to this type from the input type.
Source§

impl From<u64> for Value<'_>

Source§

fn from(n: u64) -> Self

Converts to this type from the input type.
Source§

impl From<u128> for Value<'_>

Source§

fn from(n: u128) -> Self

Converts to this type from the input type.
Source§

impl From<usize> for Value<'_>

Source§

fn from(n: usize) -> Self

Converts to this type from the input type.
Source§

impl<'a, T: Into<Value<'a>>> FromIterator<T> for Value<'a>

Source§

fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self

Collects into an array.

Source§

impl<'de> FromJson<'de> for Value<'de>

Source§

fn from_json(reader: &mut Reader<'de>) -> Result<Self, DecodeError>

Reads one value from reader, which is positioned where a value comes next. Read more
Source§

fn absent() -> Option<Self>

The value for an object member that is absent, if absence is allowed: None (absence is an error) by default, Some(None) for Option<T>, and Some(Nullable::Absent) for Nullable<T>. Read more
Source§

impl Hash for Value<'_>

Source§

fn hash<H: Hasher>(&self, state: &mut H)

Hashes consistently with ==: numbers by their text, object members in order. Iterative at any depth.

1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl<'a> Index<&str> for Value<'a>

Source§

fn index(&self, key: &str) -> &Value<'a>

The member named key, or null if this is not an object or has no such member. Never panics.

Source§

type Output = Value<'a>

The returned type after indexing.
Source§

impl<'a> Index<usize> for Value<'a>

Source§

fn index(&self, index: usize) -> &Value<'a>

The item at index, or null if this is not an array or is shorter. Never panics.

Source§

type Output = Value<'a>

The returned type after indexing.
Source§

impl PartialEq for Value<'_>

Source§

fn eq(&self, other: &Self) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl PartialEq<&str> for Value<'_>

Source§

fn eq(&self, other: &&str) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl PartialEq<String> for Value<'_>

Source§

fn eq(&self, other: &String) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl PartialEq<bool> for Value<'_>

Source§

fn eq(&self, other: &bool) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl PartialEq<f32> for Value<'_>

Source§

fn eq(&self, other: &f32) -> bool

Compares the number’s value, read as an f32 (see Number::as_f32).

1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl PartialEq<f64> for Value<'_>

Source§

fn eq(&self, other: &f64) -> bool

Compares the number’s value, so 1.0, 1, and 1e0 all equal 1.0.

1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl PartialEq<i8> for Value<'_>

Source§

fn eq(&self, other: &i8) -> bool

True when the value is an integer number equal to other.

1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl PartialEq<i16> for Value<'_>

Source§

fn eq(&self, other: &i16) -> bool

True when the value is an integer number equal to other.

1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl PartialEq<i32> for Value<'_>

Source§

fn eq(&self, other: &i32) -> bool

True when the value is an integer number equal to other.

1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl PartialEq<i64> for Value<'_>

Source§

fn eq(&self, other: &i64) -> bool

True when the value is an integer number equal to other.

1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl PartialEq<i128> for Value<'_>

Source§

fn eq(&self, other: &i128) -> bool

True when the value is an integer number equal to other.

1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl PartialEq<isize> for Value<'_>

Source§

fn eq(&self, other: &isize) -> bool

True when the value is an integer number equal to other.

1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl PartialEq<str> for Value<'_>

Source§

fn eq(&self, other: &str) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl PartialEq<u8> for Value<'_>

Source§

fn eq(&self, other: &u8) -> bool

True when the value is an integer number equal to other.

1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl PartialEq<u16> for Value<'_>

Source§

fn eq(&self, other: &u16) -> bool

True when the value is an integer number equal to other.

1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl PartialEq<u32> for Value<'_>

Source§

fn eq(&self, other: &u32) -> bool

True when the value is an integer number equal to other.

1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl PartialEq<u64> for Value<'_>

Source§

fn eq(&self, other: &u64) -> bool

True when the value is an integer number equal to other.

1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl PartialEq<u128> for Value<'_>

Source§

fn eq(&self, other: &u128) -> bool

True when the value is an integer number equal to other.

1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl PartialEq<usize> for Value<'_>

Source§

fn eq(&self, other: &usize) -> bool

True when the value is an integer number equal to other.

1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl ToJson for Value<'_>

Source§

fn to_json(&self, out: ValueWriter<'_>) -> Written

Writes self as one JSON value.
Source§

fn is_absent(&self) -> bool

Whether ObjectWriter::optional leaves this member out. false, except for Option<T>, where it is is_none(), and the pointer types, which ask what they point to. Read more

Auto Trait Implementations§

§

impl<'a> Forget for Value<'a>

§

impl<'a> Freeze for Value<'a>

§

impl<'a> Move for Value<'a>

§

impl<'a> RefUnwindSafe for Value<'a>

§

impl<'a> Send for Value<'a>

§

impl<'a> Sync for Value<'a>

§

impl<'a> Unpin for Value<'a>

§

impl<'a> UnsafeUnpin for Value<'a>

§

impl<'a> UnwindSafe for Value<'a>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.