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>
impl<'a> Object<'a>
Sourcepub fn with_capacity(capacity: usize) -> Self
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);Sourcepub fn len(&self) -> usize
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));Sourcepub fn is_empty(&self) -> bool
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()));Sourcepub fn get(&self, key: &str) -> Option<&Value<'a>>
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());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 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);Sourcepub fn contains_key(&self, key: &str) -> bool
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")));Sourcepub fn insert(
&mut self,
key: impl Into<Cow<'a, str>>,
value: impl Into<Value<'a>>,
) -> Option<Value<'a>>
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);Sourcepub fn push(
&mut self,
key: impl Into<Cow<'a, str>>,
value: impl Into<Value<'a>>,
)
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}"#);Sourcepub fn remove(&mut self, key: &str) -> Option<Value<'a>>
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"]);Sourcepub fn retain(&mut self, keep: impl FnMut(&str, &mut Value<'a>) -> bool)
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}"#);Sourcepub fn sort_keys(&mut self)
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}"#);Sourcepub fn entry(&mut self, key: impl Into<Cow<'a, str>>) -> Entry<'_, 'a>
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}"#);Sourcepub fn iter(&self) -> Iter<'_, 'a> ⓘ
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);Sourcepub fn iter_mut(&mut self) -> IterMut<'_, 'a> ⓘ
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}"#);Sourcepub fn keys(&self) -> impl DoubleEndedIterator<Item = &str> + ExactSizeIterator
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"]);Sourcepub fn values(
&self,
) -> impl DoubleEndedIterator<Item = &Value<'a>> + ExactSizeIterator
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]);Sourcepub fn as_slice(&self) -> &[(Cow<'a, str>, Value<'a>)]
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")));Sourcepub fn into_vec(self) -> Vec<(Cow<'a, str>, Value<'a>)>
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");Sourcepub fn into_owned(self) -> Object<'static>
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§
impl Eq for Object<'_>
Source§impl<'a, K: Into<Cow<'a, str>>, V: Into<Value<'a>>> Extend<(K, V)> for Object<'a>
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)
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)
fn extend_one(&mut self, item: T)
extend_one)Source§fn extend_reserve(&mut self, additional: usize)
fn extend_reserve(&mut self, additional: usize)
extend_one)