Struct RawJsonValue

Source
pub struct RawJsonValue<'text, 'a> { /* private fields */ }
Expand description

A JSON value in a RawJson.

This struct only provides the text and structural information (e.g., kind, parent, children) of this JSON value. Interpreting that text is the responsibility of the user.

To convert this JSON value to a Rust type that implements the FromRawJsonValue trait, RawJsonValue::try_to() is convinient. For other Rust types, you can use the standard FromStr trait or other parsing methods to parse the underlaying JSON text of this value as shown below:

let text = "1.23";
let json = RawJson::parse(text)?;
let raw: RawJsonValue = json.value();
let parsed: f32 =
    raw.as_number_str()?.parse().map_err(|e| JsonParseError::invalid_value(raw, e))?;
assert_eq!(parsed, 1.23);

Implementations§

Source§

impl<'text, 'a> RawJsonValue<'text, 'a>

Source

pub fn kind(self) -> JsonValueKind

Returns the kind of this JSON value.

Source

pub fn position(self) -> usize

Returns the byte position where this value begins in the JSON text (self.json().text()).

Source

pub fn json(self) -> &'a RawJson<'text>

Returns a reference to the RawJson instance that contains this value.

Source

pub fn parent(self) -> Option<Self>

Returns the parent value (array or object) that contains this value.

Source

pub fn try_to<T: FromRawJsonValue<'text>>(self) -> Result<T, JsonParseError>

Covnerts this value to T by using FromRawJsonValue::from_raw_json_value().

§Examples
let json = RawJson::parse("[1, 2, -3]")?;

// Convert via `FromRawJsonValue::from_raw_json_value()`
let (v0, v1, v2) = FromRawJsonValue::from_raw_json_value(json.value())?;
assert_eq!((v0, v1, v2), (1, 2.0, -3));

// Convert via `RawJsonValue::try_to()`
// (Exactly the same result as the above call, but usually more concise and readable)
let (v0, v1, v2) = json.value().try_to()?;
assert_eq!((v0, v1, v2), (1, 2.0, -3));
Source

pub fn as_raw_str(self) -> &'text str

Returns the raw JSON text of this value as-is.

Source

pub fn as_boolean_str(self) -> Result<&'text str, JsonParseError>

Similar to RawJsonValue::as_raw_str(), but this method verifies whether the value is a JSON boolean.

§Examples
let json = RawJson::parse("false")?;
assert_eq!(json.value().as_boolean_str()?.parse(), Ok(false));

let json = RawJson::parse("10")?;
assert!(json.value().as_boolean_str().is_err());
Source

pub fn as_integer_str(self) -> Result<&'text str, JsonParseError>

Similar to RawJsonValue::as_raw_str(), but this method verifies whether the value is a JSON integer number.

§Examples
let json = RawJson::parse("123")?;
assert_eq!(json.value().as_integer_str()?.parse(), Ok(123));

let json = RawJson::parse("12.3")?;
assert!(json.value().as_integer_str().is_err());
Source

pub fn as_float_str(self) -> Result<&'text str, JsonParseError>

Similar to RawJsonValue::as_raw_str(), but this method verifies whether the value is a JSON floating-point number.

§Examples
let json = RawJson::parse("12.3")?;
assert_eq!(json.value().as_float_str()?.parse(), Ok(12.3));

let json = RawJson::parse("123")?;
assert!(json.value().as_float_str().is_err());
Source

pub fn as_number_str(self) -> Result<&'text str, JsonParseError>

Similar to RawJsonValue::as_raw_str(), but this method verifies whether the value is a JSON number.

§Examples
let json = RawJson::parse("123")?;
assert_eq!(json.value().as_number_str()?.parse(), Ok(123));

let json = RawJson::parse("12.3")?;
assert_eq!(json.value().as_number_str()?.parse(), Ok(12.3));

let json = RawJson::parse("null")?;
assert!(json.value().as_number_str().is_err());
Source

pub fn to_unquoted_string_str(self) -> Result<Cow<'text, str>, JsonParseError>

Similar to RawJsonValue::as_raw_str(), but this method verifies whether the value is a JSON number and returns the unquoted content of the string.

§Examples
let json = RawJson::parse("\"123\"")?;
assert_eq!(json.value().to_unquoted_string_str()?, "123");
assert_eq!(json.value().to_unquoted_string_str()?.parse(), Ok(123));

let json = RawJson::parse("123")?;
assert!(json.value().to_unquoted_string_str().is_err());
Source

pub fn to_array(self) -> Result<impl Iterator<Item = Self>, JsonParseError>

If the value is a JSON array, this method returns an iterator that iterates over the array’s elements.

§Examples
let json = RawJson::parse("[0, 1, 2]")?;
for (i, v) in json.value().to_array()?.enumerate() {
    assert_eq!(v.as_integer_str()?.parse(), Ok(i));
}

let json = RawJson::parse("null")?;
assert!(json.value().to_array().is_err());
Source

pub fn to_fixed_array<const N: usize>(self) -> Result<[Self; N], JsonParseError>

If the value is a JSON array with exactly N elements, this method returns a fixed-size array containing those elements.

§Examples
let json = RawJson::parse("[0, 1, 2]")?;
let [v0, v1, v2] = json.value().to_fixed_array()?;
for (i, v) in [v0, v1, v2].into_iter().enumerate() {
    assert_eq!(v.as_integer_str()?.parse(), Ok(i));
}

let json = RawJson::parse("[0, 1]")?;
assert!(json.value().to_fixed_array::<3>().is_err());
Source

pub fn to_object( self, ) -> Result<impl Iterator<Item = (Self, Self)>, JsonParseError>

If the value is a JSON object, this method returns an iterator that iterates over the name and value pairs of the object’s members.

§Examples
let json = RawJson::parse(r#"{"a": 1, "b": 2, "c": 3}"#)?;
let mut members = json.value().to_object()?;
let (k, v) = members.next().expect("some");
assert_eq!(k.to_unquoted_string_str()?, "a");
assert_eq!(v.as_integer_str()?.parse(), Ok(1));

let json = RawJson::parse("null")?;
assert!(json.value().to_object().is_err());
Source

pub fn to_fixed_object<const N: usize, const M: usize>( self, required_member_names: [&str; N], optional_member_names: [&str; M], ) -> Result<([Self; N], [Option<Self>; M]), JsonParseError>

If the value is a JSON object, this method extracts member values for a fixed set of member names.

The method returns a tuple containing:

  • An array of values for required member names
  • An array of optional values for optional member names
§Examples
let json = RawJson::parse(r#"{"name": "Alice", "age": 30, "city": "New York"}"#)?;
let (required, optional) = json.value().to_fixed_object(
    ["name", "age"],      // required fields
    ["city", "country"]   // optional fields
)?;

assert_eq!(required[0].to_unquoted_string_str()?, "Alice");
assert_eq!(required[1].as_integer_str()?.parse(), Ok(30));

assert_eq!(optional[0].expect("some").to_unquoted_string_str()?, "New York");
assert!(optional[1].is_none()); // "country" wasn't present

// Fails when required fields are missing
let json = RawJson::parse(r#"{"name": "Bob", "city": "London"}"#)?;
assert!(json.value().to_fixed_object(["name", "age"], ["city"]).is_err());

Trait Implementations§

Source§

impl<'text, 'a> Clone for RawJsonValue<'text, 'a>

Source§

fn clone(&self) -> RawJsonValue<'text, 'a>

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<'text, 'a> Debug for RawJsonValue<'text, 'a>

Source§

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

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

impl Display for RawJsonValue<'_, '_>

Source§

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

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

impl DisplayJson for RawJsonValue<'_, '_>

Source§

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

Formats the value as JSON into the provided formatter. Read more
Source§

impl<'text, 'a> Hash for RawJsonValue<'text, 'a>

Source§

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

Feeds this value into the given Hasher. Read more
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<'text, 'a> Ord for RawJsonValue<'text, 'a>

Source§

fn cmp(&self, other: &RawJsonValue<'text, 'a>) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · Source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · Source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · Source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized,

Restrict a value to a certain interval. Read more
Source§

impl<'text, 'a> PartialEq for RawJsonValue<'text, 'a>

Source§

fn eq(&self, other: &RawJsonValue<'text, 'a>) -> 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<'text, 'a> PartialOrd for RawJsonValue<'text, 'a>

Source§

fn partial_cmp(&self, other: &RawJsonValue<'text, 'a>) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · Source§

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

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · Source§

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

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · Source§

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

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · Source§

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

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl<'text, 'a> Copy for RawJsonValue<'text, 'a>

Source§

impl<'text, 'a> Eq for RawJsonValue<'text, 'a>

Source§

impl<'text, 'a> StructuralPartialEq for RawJsonValue<'text, 'a>

Auto Trait Implementations§

§

impl<'text, 'a> Freeze for RawJsonValue<'text, 'a>

§

impl<'text, 'a> RefUnwindSafe for RawJsonValue<'text, 'a>

§

impl<'text, 'a> Send for RawJsonValue<'text, 'a>

§

impl<'text, 'a> Sync for RawJsonValue<'text, 'a>

§

impl<'text, 'a> Unpin for RawJsonValue<'text, 'a>

§

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