Skip to main content

JsonObject

Struct JsonObject 

Source
pub struct JsonObject { /* private fields */ }
Expand description

A JSON object: members in insertion order with unique keys.

Keys are guaranteed unique — the parser rejects duplicates, and insert replaces an existing key in place rather than adding a second entry. Lookup is linear; object size is bounded by JsonLimits when parsing untrusted input.

Implementations§

Source§

impl JsonObject

Source

pub fn get_str_as<'a, T>(&'a self, key: &str) -> Result<T, JsonExtractError>
where T: TryFrom<&'a str, Error = PrimitiveError>,

Extracts member key as a string-backed primitive T, validating it through T’s TryFrom<&str> constructor.

Returns JsonExtractErrorKind::Missing if the key is absent, JsonExtractErrorKind::WrongType if the member is not a JSON string, and JsonExtractErrorKind::Invalid (wrapping the PrimitiveError) if the string fails validation. The error carries the $.key path.

Source§

impl JsonObject

Source

pub fn new() -> Self

Creates an empty object.

Source

pub fn get(&self, key: &str) -> Option<&JsonValue>

Returns the value for key, if present.

Examples found in repository?
examples/basic.rs (line 23)
9fn main() {
10    // Treat this as untrusted input: parse under a conservative limit profile.
11    let input = r#"{ "service": "api", "port": 8080, "tags": ["a", "b"], "enabled": true }"#;
12    let limits = JsonLimits::conservative();
13
14    let value = match parse_with_limits(input.as_bytes(), limits) {
15        Ok(value) => value,
16        Err(err) => {
17            eprintln!("rejected: {err}");
18            return;
19        }
20    };
21
22    if let JsonValue::Object(object) = &value {
23        if let Some(port) = object.get("port").and_then(JsonValue::as_number) {
24            println!("port = {}", port.to_u64().unwrap());
25        }
26        if let Some(tags) = object.get("tags").and_then(JsonValue::as_array) {
27            println!("tags = {}", tags.len());
28        }
29    }
30
31    // Deterministic, member-order-preserving serialization.
32    println!("compact = {}", to_compact_string(&value));
33
34    // Strict by default: these are all rejected.
35    for bad in [r#"{"a":1,"a":2}"#, "{ /* c */ }", "[1,]", "NaN"] {
36        match parse_with_limits(bad.as_bytes(), limits) {
37            Ok(_) => println!("accepted (unexpected): {bad}"),
38            Err(err) => println!("rejected {bad:?}: {}", err.kind_str()),
39        }
40    }
41}
Source

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

Returns true if key is present.

Source

pub fn insert(&mut self, key: String, value: JsonValue) -> Option<JsonValue>

Inserts or replaces key. If the key already exists its value is replaced in place (preserving position) and the old value is returned; otherwise the member is appended.

Source

pub fn len(&self) -> usize

The number of members.

Source

pub fn is_empty(&self) -> bool

Returns true if the object has no members.

Source

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

Iterates over members in insertion order.

Trait Implementations§

Source§

impl Clone for JsonObject

Source§

fn clone(&self) -> JsonObject

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 JsonObject

Source§

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

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

impl Default for JsonObject

Source§

fn default() -> JsonObject

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

impl PartialEq for JsonObject

Source§

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

Tests for self and other values to be equal, and is used by ==.
1.0.0 (const: unstable) · 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 StructuralPartialEq for JsonObject

Auto Trait Implementations§

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 = 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.