Skip to main content

Object

Struct Object 

Source
pub struct Object<'a> { /* private fields */ }
Expand description

A JSON object: its members in document order.

Members are kept in a vector, in the order they were read or added, so a document is written back with its keys where they were. Lookup by key is a linear scan, which beats hashing for the small objects JSON documents are mostly made of; for a large object read once, iterate it instead of looking each key up.

Whether a parsed object can hold a key twice is up to the DuplicateKeys policy the parser used (by default a duplicate is an error). An object built in code can: insert replaces an existing member, push always appends.

§Examples

use jsonx_lib::{parse, Object, Value};

let doc = parse(r#"{"name": "jsonx", "tags": ["json"]}"#)?;
let obj: &Object = doc.as_object().unwrap();
assert_eq!(obj.get("name").and_then(Value::as_str), Some("jsonx"));
assert_eq!(obj.keys().collect::<Vec<_>>(), ["name", "tags"]);

let mut built = Object::new();
built.insert("b", 1);
built.insert("a", true);
built.insert("b", 2); // replaces in place
assert_eq!(Value::Object(built).to_string(), r#"{"b":2,"a":true}"#);

Implementations§

Source§

impl<'a> Object<'a>

Source

pub const fn new() -> Self

An empty object. Does not allocate.

§Examples
assert!(jsonx_lib::Object::new().is_empty());
Source

pub fn with_capacity(capacity: usize) -> Self

An empty object with room for capacity members.

§Examples
let mut o = jsonx_lib::Object::with_capacity(2);
o.push("k", "v");
assert_eq!(o.len(), 1);
Source

pub fn len(&self) -> usize

The number of members.

§Examples
let doc = jsonx_lib::parse(r#"{"a": 1, "b": 2}"#)?;
assert_eq!(doc.as_object().map(|o| o.len()), Some(2));
Source

pub fn is_empty(&self) -> bool

Whether the object has no members.

§Examples
let doc = jsonx_lib::parse("{}")?;
assert!(doc.as_object().is_some_and(|o| o.is_empty()));
Source

pub fn get(&self, key: &str) -> Option<&Value<'a>>

The value of the first member named key.

§Examples
let doc = jsonx_lib::parse(r#"{"id": 7}"#)?;
let obj = doc.as_object().unwrap();
assert_eq!(obj.get("id").and_then(|v| v.as_u64()), Some(7));
assert!(obj.get("missing").is_none());
Source

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

A mutable reference to the value of the first member named key.

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

let mut v = json!({ "n": 1 });
if let Some(n) = v.as_object_mut().and_then(|o| o.get_mut("n")) {
    *n = Value::from(2);
}
assert_eq!(v["n"], 2);
Source

pub fn contains_key(&self, key: &str) -> bool

Whether a member is named key.

§Examples
let doc = jsonx_lib::parse(r#"{"a": null}"#)?;
assert!(doc.as_object().is_some_and(|o| o.contains_key("a")));
Source

pub fn insert( &mut self, key: impl Into<Cow<'a, str>>, value: impl Into<Value<'a>>, ) -> Option<Value<'a>>

Sets the member named key to value, as a map would: an existing member keeps its position and its old value is returned; otherwise the member is appended and None is returned.

The existing member is found by a linear scan, so building an object of n members with insert costs O(n^2) comparisons. For a large object whose keys you know to be distinct, use push, or collect the members with FromIterator.

§Examples
use jsonx_lib::Object;

let mut o = Object::new();
assert_eq!(o.insert("a", 1), None);
assert_eq!(o.insert("a", 2), Some(1.into()));
assert_eq!(o.len(), 1);
Source

pub fn push( &mut self, key: impl Into<Cow<'a, str>>, value: impl Into<Value<'a>>, )

Appends a member without looking for an existing one with the same key. Constant time; the writer then emits both members. Use insert for map semantics.

§Examples
use jsonx_lib::{Object, Value};

let mut o = Object::new();
o.push("k", 1);
o.push("k", 2);
assert_eq!(Value::Object(o).to_string(), r#"{"k":1,"k":2}"#);
Source

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

Removes the first member named key and returns its value. The other members keep their order.

§Examples
use jsonx_lib::json;

let mut v = json!({ "a": 1, "b": 2, "c": 3 });
let obj = v.as_object_mut().unwrap();
assert_eq!(obj.remove("b"), Some(2.into()));
assert_eq!(obj.keys().collect::<Vec<_>>(), ["a", "c"]);
Source

pub fn retain(&mut self, keep: impl FnMut(&str, &mut Value<'a>) -> bool)

Keeps only the members for which keep returns true, in order; keep may change the values it keeps.

§Examples
let mut v = jsonx_lib::json!({ "a": 1, "b": null, "c": 3 });
v.as_object_mut().unwrap().retain(|_, value| !value.is_null());
assert_eq!(v.to_string(), r#"{"a":1,"c":3}"#);
Source

pub fn sort_keys(&mut self)

Sorts the members by key (byte order; members with equal keys keep their order), for output that does not depend on how the object was built.

§Examples
let mut v = jsonx_lib::json!({ "b": 1, "a": 2 });
v.as_object_mut().unwrap().sort_keys();
assert_eq!(v.to_string(), r#"{"a":2,"b":1}"#);
Source

pub fn entry(&mut self, key: impl Into<Cow<'a, str>>) -> Entry<'_, 'a>

The member named key, to read, change, or insert in one lookup (a linear scan, as for insert).

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

let mut v = json!({ "hits": 1 });
let obj = v.as_object_mut().unwrap();
for key in ["hits", "misses", "hits"] {
    let count = obj.entry(key).or_insert(0);
    *count = Value::from(count.as_i64().unwrap_or(0) + 1);
}
assert_eq!(v.to_string(), r#"{"hits":3,"misses":1}"#);
Source

pub fn iter(&self) -> Iter<'_, 'a> ⓘ

Iterates over the members as (key, value) pairs, in order.

§Examples
let doc = jsonx_lib::parse(r#"{"x": 1, "y": 2}"#)?;
let sum: i64 = doc.as_object().unwrap().iter().filter_map(|(_, v)| v.as_i64()).sum();
assert_eq!(sum, 3);
Source

pub fn iter_mut(&mut self) -> IterMut<'_, 'a> ⓘ

Iterates over the members with mutable values, in order.

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

let mut v = json!({ "a": 1, "b": 2 });
for (_, value) in v.as_object_mut().unwrap().iter_mut() {
    *value = Value::Null;
}
assert_eq!(v.to_string(), r#"{"a":null,"b":null}"#);
Source

pub fn keys(&self) -> impl DoubleEndedIterator<Item = &str> + ExactSizeIterator

The keys, in order.

§Examples
let doc = jsonx_lib::parse(r#"{"b": 1, "a": 2}"#)?;
assert_eq!(doc.as_object().unwrap().keys().collect::<Vec<_>>(), ["b", "a"]);
Source

pub fn values( &self, ) -> impl DoubleEndedIterator<Item = &Value<'a>> + ExactSizeIterator

The values, in order.

§Examples
let doc = jsonx_lib::parse(r#"{"b": 1, "a": 2}"#)?;
let values: Vec<_> = doc.as_object().unwrap().values().filter_map(|v| v.as_i64()).collect();
assert_eq!(values, [1, 2]);
Source

pub fn as_slice(&self) -> &[(Cow<'a, str>, Value<'a>)]

The members as a slice of (key, value) pairs.

§Examples
let doc = jsonx_lib::parse(r#"{"k": "v"}"#)?;
let (key, value) = &doc.as_object().unwrap().as_slice()[0];
assert_eq!((key.as_ref(), value.as_str()), ("k", Some("v")));
Source

pub fn into_vec(self) -> Vec<(Cow<'a, str>, Value<'a>)>

Takes the members out as a Vec of (key, value) pairs.

§Examples
use jsonx_lib::json;

let v = json!({ "a": 1 });
let members = v.as_object().cloned().unwrap_or_default().into_vec();
assert_eq!(members[0].0, "a");
Source

pub fn into_owned(self) -> Object<'static>

Copies every borrowed key and string so the object no longer borrows from the input. Iterative at any depth.

§Examples
use jsonx_lib::{parse, Object};

let owned: Object<'static> = {
    let text = String::from(r#"{"k": "v"}"#);
    parse(&text)?.as_object().cloned().unwrap_or_default().into_owned()
};
assert_eq!(owned["k"], "v");

Trait Implementations§

Source§

impl Clone for Object<'_>

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 Object<'_>

Source§

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

Formats the value using the given formatter. Read more
Source§

impl<'a> Default for Object<'a>

Source§

fn default() -> Self

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

impl Drop for Object<'_>

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

fn pin_drop(self: Pin<&mut Self>)

🔬This is a nightly-only experimental API. (pin_ergonomics)
Execute the destructor for this type, but different to Drop::drop, it requires self to be pinned. Read more
Source§

impl Eq for Object<'_>

Source§

impl<'a, K: Into<Cow<'a, str>>, V: Into<Value<'a>>> Extend<(K, V)> for Object<'a>

Source§

fn extend<I: IntoIterator<Item = (K, V)>>(&mut self, iter: I)

Appends the members in order, as push does.

Source§

fn extend_one(&mut self, item: T)

🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
Source§

fn extend_reserve(&mut self, additional: usize)

🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
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> From<Vec<(Cow<'a, str>, Value<'a>)>> for Object<'a>

Source§

fn from(members: Vec<(Cow<'a, str>, Value<'a>)>) -> Self

Wraps the members as given; duplicates are kept.

Source§

impl<'a, K: Into<Cow<'a, str>>, V: Into<Value<'a>>> FromIterator<(K, V)> for Object<'a>

Source§

fn from_iter<I: IntoIterator<Item = (K, V)>>(iter: I) -> Self

Appends the members in order, as push does; duplicates are kept.

Source§

impl<'de> FromJson<'de> for Object<'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 Object<'_>

Source§

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

Hashes as the Value::Object it would be: consistent with ==.

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 Object<'a>

Source§

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

The value of the first member named key, or null if there is none.

Source§

type Output = Value<'a>

The returned type after indexing.
Source§

impl<'a> IntoIterator for Object<'a>

Source§

type Item = (Cow<'a, str>, Value<'a>)

The type of the elements being iterated over.
Source§

type IntoIter = IntoIter<(Cow<'a, str>, Value<'a>)>

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
Source§

impl<'r, 'a> IntoIterator for &'r Object<'a>

Source§

type Item = (&'r str, &'r Value<'a>)

The type of the elements being iterated over.
Source§

type IntoIter = Iter<'r, 'a>

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
Source§

impl<'r, 'a> IntoIterator for &'r mut Object<'a>

Source§

type Item = (&'r str, &'r mut Value<'a>)

The type of the elements being iterated over.
Source§

type IntoIter = IterMut<'r, 'a>

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
Source§

impl PartialEq for Object<'_>

Source§

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

Members are compared in order: {"a":1,"b":2} and {"b":2,"a":1} are different documents and compare unequal.

1.0.0 (const: unstable) · Source§

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

Inequality operator !=. Read more
Source§

impl ToJson for Object<'_>

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 Object<'a>

§

impl<'a> Freeze for Object<'a>

§

impl<'a> Move for Object<'a>

§

impl<'a> RefUnwindSafe for Object<'a>

§

impl<'a> Send for Object<'a>

§

impl<'a> Sync for Object<'a>

§

impl<'a> Unpin for Object<'a>

§

impl<'a> UnsafeUnpin for Object<'a>

§

impl<'a> UnwindSafe for Object<'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, 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.