pub struct RawJsonValue<'text, 'raw> { /* private fields */ }Expand description
A JSON value in a RawJson.
This struct provides the text and structural information (e.g., kind, parent, children) of a JSON value. Interpreting that text is the responsibility of the user.
To convert this JSON value to a Rust type, you can use the standard TryFrom and TryInto traits.
For other parsing approaches, you can use the FromStr trait or other parsing methods
to parse the underlying 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| raw.invalid(e))?;
assert_eq!(parsed, 1.23);For types that implement TryFrom<RawJsonValue<'_, '_>>, you can use the TryInto trait:
let json = RawJson::parse("[1, 2, 3]")?;
let numbers: [u32; 3] = json.value().try_into()?;
assert_eq!(numbers, [1, 2, 3]);Implementations§
Source§impl<'text, 'raw> RawJsonValue<'text, 'raw>
impl<'text, 'raw> RawJsonValue<'text, 'raw>
Sourcepub fn kind(self) -> JsonValueKind
pub fn kind(self) -> JsonValueKind
Returns the kind of this JSON value.
Sourcepub fn position(self) -> usize
pub fn position(self) -> usize
Returns the byte position where this value begins in the JSON text (self.json().text()).
Sourcepub fn parent(self) -> Option<Self>
pub fn parent(self) -> Option<Self>
Returns the parent value (array or object) that contains this value.
Sourcepub fn root(self) -> Self
pub fn root(self) -> Self
Returns the root (top-level) value of the JSON data.
This method navigates back to the root value of the entire JSON structure, regardless of where this value is located in the JSON hierarchy. This is useful when you want to access other parts of the JSON from a nested value.
This operation is O(1) and more efficient than repeatedly calling parent()
to reach the root.
§Examples
let json = nojson::RawJson::parse(r#"{"user": {"name": "John", "age": 30}, "count": 42}"#)?;
let age_value = json.value()
.to_member("user")?
.required()?
.to_member("age")?
.required()?;
// From the nested age value, navigate back to the root
let root = age_value.root();
// Access any part of the original JSON structure
let count: i32 = root.to_member("count")?.required()?.try_into()?;
assert_eq!(count, 42);
let user_name: String = root
.to_member("user")?
.required()?
.to_member("name")?
.required()?
.try_into()?;
assert_eq!(user_name, "John");Sourcepub fn as_raw_str(self) -> &'text str
pub fn as_raw_str(self) -> &'text str
Returns the raw JSON text of this value as-is.
Sourcepub fn extract(self) -> RawJson<'text>
pub fn extract(self) -> RawJson<'text>
Converts this value to a borrowed RawJson containing just this value and its children.
This method creates a borrowed view of this specific JSON value and its text,
including all nested children if the value is an object or array. The resulting
RawJson contains only this value and its descendants as its root,
not the entire original JSON text.
If you need an owned version, you can call .into_owned() on the result.
§Example
let text = r#"{"user": {"name": "John", "age": 30}, "count": 42}"#;
let json = RawJson::parse(text)?;
let user_value = json.value().to_member("user")?.required()?;
// Extract the user object and its children to borrowed
let borrowed_user = user_value.extract();
// The borrowed version references the original text
assert_eq!(borrowed_user.text(), r#"{"name": "John", "age": 30}"#);
let name: String = borrowed_user.value().to_member("name")?.required()?.try_into()?;
assert_eq!(name, "John");
// Convert to owned if needed
let owned_user = borrowed_user.into_owned();Sourcepub fn as_boolean_str(self) -> Result<&'text str, JsonParseError>
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());Sourcepub fn as_integer_str(self) -> Result<&'text str, JsonParseError>
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());Sourcepub fn as_float_str(self) -> Result<&'text str, JsonParseError>
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());Sourcepub fn as_number_str(self) -> Result<&'text str, JsonParseError>
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());Sourcepub fn to_unquoted_string_str(self) -> Result<Cow<'text, str>, JsonParseError>
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 string 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());Sourcepub fn to_array(self) -> Result<impl Iterator<Item = Self>, JsonParseError>
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());§Note
For converting to a fixed-size array, you can use the TryInto trait instead:
let json = RawJson::parse("[0, 1, 2]")?;
let fixed_array: [usize; 3] = json.value().try_into()?;Sourcepub fn to_object(
self,
) -> Result<impl Iterator<Item = (Self, Self)>, JsonParseError>
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());Sourcepub fn to_member<'a>(
self,
name: &'a str,
) -> Result<RawJsonMember<'text, 'raw, 'a>, JsonParseError>
pub fn to_member<'a>( self, name: &'a str, ) -> Result<RawJsonMember<'text, 'raw, 'a>, JsonParseError>
Attempts to access a member of a JSON object by name.
This method returns a RawJsonMember that represents the result of
looking up the specified member name. The member may or may not exist,
and you can use methods like RawJsonMember::required() or convert
it to an Option<T> to handle both cases.
§Examples
let json = RawJson::parse(r#"{"name": "Alice", "age": 30}"#)?;
let obj = json.value();
// Access existing member
let name_value: String = obj.to_member("name")?.required()?.try_into()?;
assert_eq!(name_value, "Alice");
// Handle optional member
let city_member = obj.to_member("city")?;
let city: Option<String> = city_member.try_into()?;
assert_eq!(city, None);§Performance
This method has O(n) complexity where n is the number of members in the object,
as it performs a linear search through all object members to find the requested name.
If you need to access multiple members from the same object, consider using
RawJsonValue::to_object() instead, which allows you to iterate through
all members once and extract the values you need more efficiently.
let json = RawJson::parse(r#"{"name": "Alice", "age": 30, "city": "New York"}"#)?;
let obj = json.value();
// Efficient: single iteration for multiple members
let mut name = None;
let mut age = None;
let mut city = None;
for (key, value) in obj.to_object()? {
match key.to_unquoted_string_str()?.as_ref() {
"name" => name = Some(value),
"age" => age = Some(value),
"city" => city = Some(value),
_ => {}
}
}Sourcepub fn map<F, T>(self, f: F) -> Result<T, JsonParseError>
pub fn map<F, T>(self, f: F) -> Result<T, JsonParseError>
Applies a transformation function to this JSON value.
This method allows you to transform a RawJsonValue into any other type T
using a closure that can potentially fail with a JsonParseError. It’s particularly
useful for chaining operations or applying custom parsing logic.
§Examples
let json = RawJson::parse("\"42\"")?;
// Transform a string value to an integer
let number: i32 = json.value().map(|v| {
v.to_unquoted_string_str()?.parse().map_err(|e| v.invalid(e))
})?;
assert_eq!(number, 42);This method is equivalent to directly calling the function with the value, but provides a more functional programming style for chaining operations.
Sourcepub fn invalid<E>(self, error: E) -> JsonParseError
pub fn invalid<E>(self, error: E) -> JsonParseError
Creates a JsonParseError::InvalidValue error for this value.
This is a convenience method that’s equivalent to calling
JsonParseError::invalid_value() with this value.
§Examples
let json = RawJson::parse("\"not_a_number\"")?;
let value = json.value();
// These are equivalent:
let error1 = value.invalid("expected a number");
let error2 = nojson::JsonParseError::invalid_value(value, "expected a number");Trait Implementations§
Source§impl<'text, 'raw> Clone for RawJsonValue<'text, 'raw>
impl<'text, 'raw> Clone for RawJsonValue<'text, 'raw>
Source§fn clone(&self) -> RawJsonValue<'text, 'raw>
fn clone(&self) -> RawJsonValue<'text, 'raw>
1.0.0 · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source. Read more