sonic_rs::value::object

Struct Object

Source
pub struct Object(/* private fields */);
Expand description

Represents the JSON object. The inner implement is a key-value array. Its order is as same as origin JSON.

§Examples

use sonic_rs::{from_str, Object};

let mut obj: Object = from_str(r#"{"a": 1, "b": true, "c": null}"#).unwrap();

assert_eq!(obj["a"], 1);
assert_eq!(obj.insert(&"d", "e"), None);
assert_eq!(obj["d"], "e");
assert_eq!(obj.len(), 4);

§Warning

The key in Object is not sorted and the get operation is O(n). And Object is allowed to have duplicated keys.

§Examples

use sonic_rs::{from_str, Object};

let obj: Object = from_str(r#"{"a": 1, "a": true, "a": null}"#).unwrap();

assert_eq!(obj["a"], 1);
assert_eq!(obj.len(), 3); // allow duplicated keys

If you care about that, recommend to use HashMap or BTreeMap instead. The parse performance is slower than Object.

Implementations§

Source§

impl Object

Source

pub fn into_value(self) -> Value

Returns the inner Value.

Source

pub fn new() -> Object

Create a new empty object.

§Example
use sonic_rs::{from_str, json, object, prelude::*, Object};

let mut obj: Object = from_str("{}").unwrap();
obj.insert(&"arr", object! {});
obj.insert(&"a", 1);
obj.insert(&"arr2", Object::new());
obj["a"] = json!(123);
obj["arr2"] = json!("hello world");

assert_eq!(obj["a"], 123);
assert_eq!(obj["arr2"], "hello world");
Source

pub fn with_capacity(capacity: usize) -> Self

Create a new empty object with capacity.

Source

pub fn clear(&mut self)

Clear the object, make it as empty but keep the allocated memory.

§Examples
use sonic_rs::{json, object};

let mut obj = object! {"a": 1, "b": true, "c": null};
obj.clear();
assert!(obj.is_empty());
assert!(obj.capacity() >= 3);
Source

pub fn capacity(&self) -> usize

Returns the capacity of the object.

Source

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

Returns a reference to the value corresponding to the key.

The key may be AsRef<str>.

§Examples
use sonic_rs::{json, object};

let mut obj = object! {"a": 1, "b": true, "c": null};
obj.insert(&"d", "e");
assert_eq!(obj.get(&"d").unwrap(), "e");
assert_eq!(obj.get(&"f"), None);
assert_eq!(obj.get(&"a").unwrap(), 1);
Source

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

Returns true if the map contains a value for the specified key.

The key may be AsRef<str>.

§Examples
use sonic_rs::object;

let mut obj = object! {"a": 1, "b": true, "c": null};
obj.insert(&"d", "e");
assert_eq!(obj.contains_key(&"d"), true);
assert_eq!(obj.contains_key(&"a"), true);
assert_eq!(obj.contains_key(&"e"), false);
Source

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

Returns a mutable reference to the value corresponding to the key.

The key may be AsRef<str>.

§Examples
use sonic_rs::object;

let mut obj = object! {"a": 1, "b": true, "c": null};
obj.insert(&"d", "e");

*(obj.get_mut(&"d").unwrap()) = "f".into();
assert_eq!(obj.contains_key(&"d"), true);
assert_eq!(obj["d"], "f");
Source

pub fn get_key_value<Q: AsRef<str>>(&self, key: &Q) -> Option<(&str, &Value)>

Returns the key-value pair corresponding to the supplied key.

The key may be AsRef<str>.

§Examples
use sonic_rs::{object, Value};

let mut obj = object! {"a": 1, "b": true, "c": null};
obj.insert(&"d", "e");

assert_eq!(obj.get_key_value(&"d").unwrap(), ("d", &Value::from("e")));
assert_eq!(obj.get_key_value(&"a").unwrap(), ("a", &Value::from(1)));
assert_eq!(obj.get_key_value(&"e"), None);
Source

pub fn insert<K: AsRef<str> + ?Sized, V: Into<Value>>( &mut self, key: &K, value: V, ) -> Option<Value>

Inserts a key-value pair into the object. The Value is converted from V.

The key may be AsRef<str>.

If the object did not have this key present, None is returned.

If the object did have this key present, the value is updated, and the old value is returned. The key is not updated, though; this matters for types that can be == without being identical. See the [module-level documentation] for more.

§Examples
use sonic_rs::{json, object, Value};

let mut obj = object! {"a": 1, "b": true, "c": null};
assert_eq!(obj.len(), 3);
assert_eq!(obj.insert(&"d", "e"), None);
assert_eq!(obj.len(), 4);
assert_eq!(obj["d"], "e");
assert_eq!(obj.insert(&"d", "f").unwrap(), "e");
assert_eq!(obj["d"], "f");
assert_eq!(obj.len(), 4);
assert_eq!(obj.insert(&"d", json!("h")).unwrap(), "f");
assert_eq!(obj["d"], "h");
assert_eq!(obj.insert(&"i", Value::from("j")), None);
assert_eq!(obj.len(), 5);
Source

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

Removes a key from the object, returning the value at the key if the key was previously in the object.

The key may be AsRef<str>.

§Examples
use sonic_rs::object;

let mut obj = object! {"a": 1, "b": true, "c": null};
assert_eq!(obj.remove(&"d"), None);
assert_eq!(obj.remove(&"a").unwrap(), 1);
Source

pub fn remove_entry<'k, Q: AsRef<str>>( &mut self, key: &'k Q, ) -> Option<(&'k str, Value)>

Removes a key from the object, returning the stored key and value if the key was previously in the obj.

The key may be AsRef<str>.

§Examples
use sonic_rs::object;

let mut obj = object! {"a": 1, "b": true, "c": null};
assert_eq!(obj.remove_entry(&"d"), None);
let (key, val) = obj.remove_entry(&"a").unwrap();
assert_eq!(key, "a");
assert_eq!(val, 1);
Source

pub fn len(&self) -> usize

Returns the number of key-value paris in the object.

Source

pub fn is_empty(&self) -> bool

Returns true if the object contains no key-value pairs.

Source

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

Returns an immutable iterator over the key-value pairs of the object.

§Examples
use sonic_rs::object;

let obj = object! {"a": 1, "b": true, "c": null};

for (key, value) in obj.iter() {
    println!("{}: {}", key, value);
}
Source

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

Returns an mutable iterator over the key-value pairs of the object.

§Examples
use sonic_rs::{object, Value};

let mut obj = object! {"a": 1, "b": true, "c": null};

for (key, value) in obj.iter_mut() {
    *value = Value::from(key);
}

assert_eq!(obj["a"], "a");
assert_eq!(obj["b"], "b");
assert_eq!(obj["c"], "c");
Source

pub fn entry<'a, Q: AsRef<str> + ?Sized>(&'a mut self, key: &Q) -> Entry<'a>

Gets the given key’s corresponding entry in the object for in-place manipulation.

§Examples
use sonic_rs::{object, Value};

let mut obj = object! {};

for i in 0..10 {
    obj.entry(&i.to_string()).or_insert(1);
}

for i in 0..10 {
    obj.entry(&i.to_string())
        .and_modify(|v| *v = Value::from(i + 1));
}

assert_eq!(obj[&"1"], 2);
assert_eq!(obj[&"2"], 3);
assert_eq!(obj[&"3"], 4);
assert_eq!(obj.get(&"10"), None);
Source

pub fn retain<F>(&mut self, f: F)
where F: FnMut(&str, &mut Value) -> bool,

Retains only the elements specified by the predicate.

In other words, remove all pairs (k, v) for which f(&k, &mut v) returns false. The elements are visited in unsorted (and unspecified) order.

§Examples
use sonic_rs::object;

let mut obj = object! {"a": 1, "b": true, "c": null};
obj.retain(|key, _| key == "a");
assert_eq!(obj.len(), 1);
assert_eq!(obj["a"], 1);
Source

pub fn append(&mut self, other: &mut Self)

Moves all elements from other into self, leaving other empty.

§Examples
use sonic_rs::{json, object};

let mut a = object! {};
let mut b = object! {"a": null, "b": 1};
a.append(&mut b);

assert_eq!(a, object! {"a": null, "b": 1});
assert!(b.is_empty());
Source

pub fn reserve(&mut self, additional: usize)

Reserves capacity for at least additional more elements to be inserted in the given.

§Examples
use sonic_rs::object;
let mut obj = object! {};
obj.reserve(1);
assert!(obj.capacity() >= 1);

obj.reserve(10);
assert!(obj.capacity() >= 10);

Trait Implementations§

Source§

impl Clone for Object

Source§

fn clone(&self) -> Object

Returns a copy of the value. Read more
1.0.0 · 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 Default for Object

Source§

fn default() -> Self

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

impl<'de> Deserialize<'de> for Object

Source§

fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl<'a, K: AsRef<str> + ?Sized, V: Clone + Debug + Into<Value> + 'a> Extend<(&'a K, &'a V)> for Object

Source§

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

Extend a Object with the contents of an iterator.

§Examples
use std::collections::HashMap;

use sonic_rs::{json, object, Object, Value};

let mut obj = object![];
let mut map: HashMap<&str, Value> = {
    let mut map = HashMap::new();
    map.insert("sonic", json!(40));
    map.insert("rs", json!(null));
    map
};

obj.extend(&map);
assert_eq!(obj, object! {"sonic": 40, "rs": null});

obj.extend(&object! {"object": [1, 2, 3]});
assert_eq!(obj, object! {"sonic": 40, "rs": null, "object": [1, 2, 3]});
Source§

fn extend_one(&mut self, item: A)

🔬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 From<Object> for Value

Source§

fn from(val: Object) -> Self

Converts to this type from the input type.
Source§

impl<'a, K: AsRef<str>, V: Clone + Into<Value> + 'a> FromIterator<(K, &'a V)> for Object

Source§

fn from_iter<T: IntoIterator<Item = (K, &'a V)>>(iter: T) -> Self

Create a Object by collecting an iterator of key-value pairs.

§Examples
use std::collections::HashMap;

use sonic_rs::{object, Object, Value};

let mut map = HashMap::new();
map.insert("sonic_rs", 40);
map.insert("json", 2);

let x: Object = map.iter().collect();
assert_eq!(x, object! {"sonic_rs": 40, "json": 2});

let x = Object::from_iter(&object! {"sonic_rs": 40, "json": 2});
assert_eq!(x, object! {"sonic_rs": 40, "json": 2});
Source§

impl<'a, Q: AsRef<str> + ?Sized> Index<&'a Q> for Object

Source§

type Output = Value

The returned type after indexing.
Source§

fn index(&self, index: &'a Q) -> &Self::Output

Performs the indexing (container[index]) operation. Read more
Source§

impl<'a, Q: AsRef<str> + ?Sized> IndexMut<&'a Q> for Object

Source§

fn index_mut(&mut self, index: &'a Q) -> &mut Self::Output

Performs the mutable indexing (container[index]) operation. Read more
Source§

impl<'a> IntoIterator for &'a Object

Source§

type Item = (&'a str, &'a Value)

The type of the elements being iterated over.
Source§

type IntoIter = Iter<'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<'a> IntoIterator for &'a mut Object

Source§

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

The type of the elements being iterated over.
Source§

type IntoIter = IterMut<'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<Object> for &Value

Source§

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

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

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

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl PartialEq<Object> for &mut Value

Source§

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

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

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

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl PartialEq<Object> for Value

Source§

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

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

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

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl PartialEq<Value> for &Object

Source§

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

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

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

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl PartialEq<Value> for &mut Object

Source§

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

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

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

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl PartialEq<Value> for Object

Source§

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

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

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

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl PartialEq for Object

Source§

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

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

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

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl Serialize for Object

Source§

fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,

Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations§

§

impl Freeze for Object

§

impl !RefUnwindSafe for Object

§

impl Send for Object

§

impl Sync for Object

§

impl Unpin for Object

§

impl !UnwindSafe for Object

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, dst: *mut T)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. 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 = Infallible

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

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

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,