JsonValue

Struct JsonValue 

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

A JSON value with fluent builder API and lazy parsing.

§Lazy Parsing

When created via json::try_parse(), the value starts in lazy mode. The path_* methods scan the raw bytes without building a full tree, which is 10-40x faster when you only need a few fields.

Operations that require the full tree (get(), at(), keys(), etc.) trigger a full parse on first access, which is then cached.

§Thread Safety

JsonValue uses Rc<Value> internally and is not Send or Sync. It cannot be shared across threads. This is intentional for WASM targets where single-threaded execution is the norm and Rc provides cheaper reference counting than Arc.

If you need thread-safe JSON values, consider using a different JSON library like serde_json with its thread-safe Value type.

Implementations§

Source§

impl JsonValue

Source

pub fn get(&self, key: &str) -> Self

Get object field (returns null if missing or not an object).

Note: This triggers a full parse if in lazy mode. For extracting specific fields, prefer path_str(), path_int(), etc. which use lazy scanning.

Source

pub fn at(&self, index: usize) -> Self

Get array element (returns null if out of bounds or not an array).

Note: This triggers a full parse if in lazy mode and clones the underlying Value. For parsing large arrays, use map_array() or try_map_array() instead for better performance.

Source

pub fn map_array<T, F>(&self, f: F) -> Option<Vec<T>>
where F: Fn(&Value) -> Option<T>,

Process array elements without per-element cloning.

This is more efficient than calling at(i) in a loop because it avoids cloning each element’s Value. Returns None if not an array.

Note: This triggers a full parse if in lazy mode.

§Example
let value = json::arr()
    .push(json::str("hello"))
    .push(json::str("world"));
let strings: Option<Vec<String>> = value.map_array(|v| {
    match v {
        RawValue::String(s) => Some(s.clone()),
        _ => None,
    }
});
assert_eq!(strings, Some(vec!["hello".to_string(), "world".to_string()]));
Source

pub fn try_map_array<T, E, F>(&self, f: F) -> Option<Result<Vec<T>, E>>
where F: Fn(&Value) -> Result<T, E>,

Process array elements with error handling, without per-element cloning.

Like map_array(), but the function can return errors. Returns None if not an array, Some(Err(_)) if parsing fails.

Note: This triggers a full parse if in lazy mode.

Source

pub fn from_raw(value: &Value) -> Self

Wrap a raw Value reference in a temporary JsonValue for parsing.

This is useful inside map_array/try_map_array callbacks when you need to use JsonValue methods like get() or str().

Note: The returned JsonValue clones the Value, so use sparingly.

Source

pub fn str(&self) -> Option<String>

As string, None if not a string.

Source

pub fn str_or(&self, default: &str) -> String

As string, or default if not a string.

Source

pub fn int(&self) -> Option<i64>

As integer, None if not a number.

Source

pub fn int_or(&self, default: i64) -> i64

As integer, or default if not a number.

Source

pub fn float(&self) -> Option<f64>

As float, None if not a number.

§Precision Warning

Converting large integers to f64 may lose precision. Integers with absolute value > 2^53 (9,007,199,254,740,992) cannot be represented exactly in f64. For large integers, use int() instead.

Non-finite values (NaN, Infinity) return None.

Source

pub fn float_or(&self, default: f64) -> f64

As float, or default if not a number.

See float() for precision warnings.

Source

pub fn bool(&self) -> Option<bool>

As boolean, None if not a boolean.

Source

pub fn bool_or(&self, default: bool) -> bool

As boolean, or default if not a boolean.

Source

pub fn is_null(&self) -> bool

Is this value null?

Source

pub fn keys(&self) -> Vec<String>

Get object keys (empty if not an object).

Note: This triggers a full parse if in lazy mode.

Source

pub fn len(&self) -> Option<usize>

Get array/object length.

Note: This triggers a full parse if in lazy mode.

Source

pub fn is_empty(&self) -> bool

Is this an empty array/object?

Note: This triggers a full parse if in lazy mode.

Source

pub fn path_str(&self, path: &[&str]) -> Option<String>

Get string at path.

When in lazy mode, this scans the raw bytes without parsing the full tree. This is 10-40x faster than full parsing when you only need a few fields.

§Example
let body = br#"{"user":{"name":"Alice"}}"#;
let parsed = json::try_parse(body).unwrap();
let name = parsed.path_str(&["user", "name"]);  // Lazy scan: ~500ns
assert_eq!(name, Some("Alice".to_string()));
Source

pub fn path_str_or(&self, path: &[&str], default: &str) -> String

Get string at path, or default.

Source

pub fn path_int(&self, path: &[&str]) -> Option<i64>

Get integer at path.

When in lazy mode, this scans the raw bytes without parsing the full tree.

Source

pub fn path_int_or(&self, path: &[&str], default: i64) -> i64

Get integer at path, or default.

Source

pub fn path_float(&self, path: &[&str]) -> Option<f64>

Get float at path.

When in lazy mode, this scans the raw bytes without parsing the full tree.

Source

pub fn path_float_or(&self, path: &[&str], default: f64) -> f64

Get float at path, or default.

Source

pub fn path_bool(&self, path: &[&str]) -> Option<bool>

Get boolean at path.

When in lazy mode, this scans the raw bytes without parsing the full tree.

Source

pub fn path_bool_or(&self, path: &[&str], default: bool) -> bool

Get boolean at path, or default.

Source

pub fn path_is_null(&self, path: &[&str]) -> bool

Check if value at path is null.

When in lazy mode, this scans the raw bytes without parsing the full tree.

Source

pub fn path_exists(&self, path: &[&str]) -> bool

Check if path exists (even if null).

When in lazy mode, this scans the raw bytes without parsing the full tree.

Source

pub fn set(self, key: &str, value: Self) -> Self

Set object field (creates object if needed).

Uses copy-on-write via Rc::make_mut - only clones the object if there are multiple references. For typical builder patterns like obj().set("a", v1).set("b", v2), this is O(1) per set, not O(n).

Source

pub fn push(self, value: Self) -> Self

Push to array (creates array if needed).

Uses copy-on-write via Rc::make_mut - only clones the array if there are multiple references. For typical builder patterns like arr().push(v1).push(v2), this is O(1) per push, not O(n).

Source

pub fn to_bytes(&self) -> Vec<u8>

Serialize to JSON bytes.

Trait Implementations§

Source§

impl Clone for JsonValue

Source§

fn clone(&self) -> JsonValue

Returns a duplicate 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 JsonValue

Source§

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

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

impl Display for JsonValue

Source§

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

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

impl ToJson for JsonValue

Source§

fn to_json(&self) -> JsonValue

Convert this value to a JSON value.

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