pub struct RawJsonb<'a> { /* private fields */ }
Expand description
Represents JSONB data wrapped around a raw, immutable slice of bytes.
It does not own the underlying data, allowing various operations to be performed on the JSONB data without copying.
This is critical for performance when dealing with large JSONB values.
RawJsonb
provides various methods to inspect and manipulate the JSONB data efficiently.
Implementations§
Source§impl RawJsonb<'_>
impl RawJsonb<'_>
Sourcepub fn array_length(&self) -> Result<Option<usize>, Error>
pub fn array_length(&self) -> Result<Option<usize>, Error>
Returns the number of elements in a JSONB array.
If the JSONB data is an array, this function returns the number of elements in the array.
If the JSONB data is not an array (e.g., it’s an object or a scalar), this function returns None
.
An error is returned if the JSONB data is invalid.
§Arguments
self
- The JSONB value.
§Returns
Ok(Some(usize))
- the number of elements in the array.Ok(None)
- If the input is not an array.Err(Error)
- If the input JSONB data is invalid.
§Examples
use jsonb::OwnedJsonb;
let arr_jsonb = "[1,2,3]".parse::<OwnedJsonb>().unwrap();
let raw_jsonb = arr_jsonb.as_raw();
let len = raw_jsonb.array_length().unwrap();
assert_eq!(len, Some(3));
let obj_jsonb = r#"{"a": 1, "b": {"c": 2, "d": 3}}"#.parse::<OwnedJsonb>().unwrap();
let raw_jsonb = obj_jsonb.as_raw();
let len = raw_jsonb.array_length().unwrap();
assert_eq!(len, None);
Sourcepub fn array_values(&self) -> Result<Option<Vec<OwnedJsonb>>, Error>
pub fn array_values(&self) -> Result<Option<Vec<OwnedJsonb>>, Error>
Extracts the values from a JSONB array.
If the JSONB value is an array, this function returns a vector of OwnedJsonb
representing the array elements.
If the JSONB value is not an array (e.g., it’s an object or a scalar), this function returns None
.
§Arguments
self
- The JSONB value.
§Returns
Ok(Some(Vec<OwnedJsonb>))
- A vector ofOwnedJsonb
values if the input is an array.Ok(None)
- If the input is not an array.Err(Error)
- If the input JSONB data is invalid.
§Examples
use jsonb::OwnedJsonb;
// Array values extraction
let arr_jsonb = r#"[1, "hello", {"a": 1}]"#.parse::<OwnedJsonb>().unwrap();
let raw_jsonb = arr_jsonb.as_raw();
let values_result = raw_jsonb.array_values();
assert!(values_result.is_ok());
let values = values_result.unwrap().unwrap();
assert_eq!(values.len(), 3);
assert_eq!(values[0].to_string(), "1");
assert_eq!(values[1].to_string(), r#""hello""#);
assert_eq!(values[2].to_string(), r#"{"a":1}"#);
// Object - returns None
let obj_jsonb = r#"{"a": 1}"#.parse::<OwnedJsonb>().unwrap();
let raw_jsonb = obj_jsonb.as_raw();
let values_result = raw_jsonb.array_values();
assert!(values_result.is_ok());
assert!(values_result.unwrap().is_none());
// Scalar - returns None
let scalar_jsonb = "1".parse::<OwnedJsonb>().unwrap();
let raw_jsonb = scalar_jsonb.as_raw();
let values_result = raw_jsonb.array_values();
assert!(values_result.is_ok());
assert!(values_result.unwrap().is_none());
Sourcepub fn array_distinct(&self) -> Result<OwnedJsonb, Error>
pub fn array_distinct(&self) -> Result<OwnedJsonb, Error>
Returns a JSONB array with duplicate elements removed.
This function takes a JSONB value as input and returns a new JSONB array containing only the unique elements from the input.
The behavior depends on the input type:
- Array: Returns a new array containing only the unique elements from the input array.
- Object/Scalar: Returns a new array containing the original object or salar as its only element.
- Invalid JSONB: Returns an error.
§Arguments
self
- The JSONB value.
§Returns
Ok(OwnedJsonb)
- A JSONB array containing only the unique elements from the input.Err(Error)
- If the input JSONB data is invalid.
§Examples
use jsonb::OwnedJsonb;
// Array with duplicates
let arr_jsonb = r#"[1, 2, 2, 3, 1, 4]"#.parse::<OwnedJsonb>().unwrap();
let distinct = arr_jsonb.as_raw().array_distinct().unwrap();
assert_eq!(distinct.to_string(), "[1,2,3,4]"); // Order may vary
// Array with only unique elements
let arr_jsonb = r#"[1, 2, 3, 4]"#.parse::<OwnedJsonb>().unwrap();
let distinct = arr_jsonb.as_raw().array_distinct().unwrap();
assert_eq!(distinct.to_string(), "[1,2,3,4]"); // Order may vary
// Object
let obj_jsonb = r#"{"a": 1}"#.parse::<OwnedJsonb>().unwrap();
let distinct = obj_jsonb.as_raw().array_distinct().unwrap();
assert_eq!(distinct.to_string(), r#"[{"a":1}]"#);
// Scalar
let scalar_jsonb = "1".parse::<OwnedJsonb>().unwrap();
let distinct = scalar_jsonb.as_raw().array_distinct().unwrap();
assert_eq!(distinct.to_string(), "[1]");
// Invalid JSONB data
let invalid_jsonb = OwnedJsonb::new(vec![1, 2, 3, 4]);
let invalid_raw_jsonb = invalid_jsonb.as_raw();
let result = invalid_raw_jsonb.array_distinct();
assert!(result.is_err());
Sourcepub fn array_intersection(
&self,
other: &RawJsonb<'_>,
) -> Result<OwnedJsonb, Error>
pub fn array_intersection( &self, other: &RawJsonb<'_>, ) -> Result<OwnedJsonb, Error>
Computes the intersection of two JSONB arrays or the containment check for objects and scalars.
This function calculates the intersection of two JSONB arrays or checks if one JSONB value is contained within another.
The behavior depends on the input types:
- Array + Array: Returns a new array containing only the elements that are present in both input arrays. The order of elements is not guaranteed. Duplicate elements are handled correctly, the multiplicity of elements in the intersection is the minimum of their multiplicities in the input arrays.
- Object/Scalar + Object/Scalar: Returns a new array containing the
self
value only if it’s present in theother
value. - Invalid input: Returns an error if either input is not an array, object, or scalar.
§Arguments
self
- The first JSONB value.other
- The second JSONB value.
§Returns
Ok(OwnedJsonb)
- The intersection array (for array + array) or a single-element array indicating containment (for other combinations).Err(Error)
- If any of the input JSONB data is invalid.
§Examples
use jsonb::OwnedJsonb;
// Array intersection
let arr1 = r#"[1, 2, 2, 3]"#.parse::<OwnedJsonb>().unwrap();
let arr2 = r#"[2, 3, 4]"#.parse::<OwnedJsonb>().unwrap();
let intersection = arr1.as_raw().array_intersection(&arr2.as_raw()).unwrap();
assert_eq!(intersection.to_string(), "[2,3]"); // Order may vary, duplicates handled
let arr1 = r#"[1, 1, 2, 3]"#.parse::<OwnedJsonb>().unwrap();
let arr2 = r#"[1, 1, 1, 3]"#.parse::<OwnedJsonb>().unwrap();
let intersection = arr1.as_raw().array_intersection(&arr2.as_raw()).unwrap();
assert_eq!(intersection.to_string(), "[1,1,3]"); // Order may vary
// Object containment (checks for complete equality)
let obj1 = r#"{"a": 1}"#.parse::<OwnedJsonb>().unwrap();
let obj2 = r#"{"a": 1}"#.parse::<OwnedJsonb>().unwrap();
let contained = obj1.as_raw().array_intersection(&obj2.as_raw()).unwrap();
assert_eq!(contained.to_string(), r#"[{"a":1}]"#);
let obj1 = r#"{"a": 1}"#.parse::<OwnedJsonb>().unwrap();
let obj2 = r#"{"a": 2}"#.parse::<OwnedJsonb>().unwrap();
let contained = obj1.as_raw().array_intersection(&obj2.as_raw()).unwrap();
assert_eq!(contained.to_string(), "[]"); // Not contained
let scalar1 = "1".parse::<OwnedJsonb>().unwrap();
let scalar2 = "1".parse::<OwnedJsonb>().unwrap();
let contained = scalar1
.as_raw()
.array_intersection(&scalar2.as_raw())
.unwrap();
assert_eq!(contained.to_string(), "[1]"); // Contained
let scalar1 = "1".parse::<OwnedJsonb>().unwrap();
let scalar2 = "2".parse::<OwnedJsonb>().unwrap();
let contained = scalar1
.as_raw()
.array_intersection(&scalar2.as_raw())
.unwrap();
assert_eq!(contained.to_string(), "[]"); // Not contained
Sourcepub fn array_except(&self, other: &RawJsonb<'_>) -> Result<OwnedJsonb, Error>
pub fn array_except(&self, other: &RawJsonb<'_>) -> Result<OwnedJsonb, Error>
Computes the set difference between two JSONB arrays or checks for non-containment of objects and scalars.
This function calculates the set difference between two JSONB arrays or checks if one JSONB value is not contained within another.
The behavior depends on the input types:
- Array + Array: Returns a new array containing only the elements that are present in the
self
array but not in theother
array. The order of elements is not guaranteed. Duplicate elements are handled correctly, if an element appears multiple times inself
but is present inother
, it will be removed from the result only up to the number of times it appears inother
. - Object/Scalar + Object/Scalar: Returns a new array containing the
self
value if it’s not contained in theother
value. - Invalid input: Returns an error if either input is not an array, object, or scalar.
§Arguments
self
- The first JSONB value.other
- The second JSONB value.
§Returns
Ok(OwnedJsonb)
- The resulting array after removing elements fromself
that are present inother
.Err(Error)
- If any of the input JSONB data is invalid.
§Examples
use jsonb::OwnedJsonb;
// Array except
let arr1 = r#"[1, 2, 2, 3]"#.parse::<OwnedJsonb>().unwrap();
let arr2 = r#"[2, 3, 4]"#.parse::<OwnedJsonb>().unwrap();
let except = arr1.as_raw().array_except(&arr2.as_raw()).unwrap();
assert_eq!(except.to_string(), "[1,2]"); // Order may vary, duplicates handled
let arr1 = r#"[1, 1, 2, 3, 3]"#.parse::<OwnedJsonb>().unwrap();
let arr2 = r#"[1, 3, 3]"#.parse::<OwnedJsonb>().unwrap();
let except = arr1.as_raw().array_except(&arr2.as_raw()).unwrap();
assert_eq!(except.to_string(), "[1,2]"); // Order may vary
// Object non-containment
let obj1 = r#"{"a": 1}"#.parse::<OwnedJsonb>().unwrap();
let obj2 = r#"{"a": 1}"#.parse::<OwnedJsonb>().unwrap();
let not_contained = obj1.as_raw().array_except(&obj2.as_raw()).unwrap();
assert_eq!(not_contained.to_string(), "[]"); // Completely contained
let obj1 = r#"{"a": 1}"#.parse::<OwnedJsonb>().unwrap();
let obj2 = r#"{"a": 2}"#.parse::<OwnedJsonb>().unwrap();
let not_contained = obj1.as_raw().array_except(&obj2.as_raw()).unwrap();
assert_eq!(not_contained.to_string(), r#"[{"a":1}]"#); // Not contained
let scalar1 = "1".parse::<OwnedJsonb>().unwrap();
let scalar2 = "1".parse::<OwnedJsonb>().unwrap();
let not_contained = scalar1.as_raw().array_except(&scalar2.as_raw()).unwrap();
assert_eq!(not_contained.to_string(), "[]"); // Contained
let scalar1 = "1".parse::<OwnedJsonb>().unwrap();
let scalar2 = "2".parse::<OwnedJsonb>().unwrap();
let not_contained = scalar1.as_raw().array_except(&scalar2.as_raw()).unwrap();
assert_eq!(not_contained.to_string(), "[1]"); // Not contained
Sourcepub fn array_overlap(&self, other: &RawJsonb<'_>) -> Result<bool, Error>
pub fn array_overlap(&self, other: &RawJsonb<'_>) -> Result<bool, Error>
Checks if two JSONB arrays or a JSONB array and an object/scalar have any elements in common.
This function determines whether two JSONB arrays, or a JSONB array and an object/scalar, share any common elements.
The behavior depends on the input types:
- Array + Array: Returns
true
if the two arrays have at least one element in common; otherwise, returnsfalse
. - Array + Object/Scalar: Returns
true
if the array contains the object/scalar; otherwise, returnsfalse
. - Object/Scalar + Array: Returns
true
if the array contains the object/scalar; otherwise, returnsfalse
. - Object/Scalar + Object/Scalar: Returns
true
only if both values are exactly equal. This is effectively an equality check. - Invalid input: Returns an error if either input is invalid JSONB data.
§Arguments
self
- The first JSONB value.other
- The second JSONB value.
§Returns
Ok(true)
- If the two JSONB values have at least one element in common.Ok(false)
- If the two JSONB values have no elements in common.Err(Error)
- If any of the input JSONB data is invalid.
§Examples
use jsonb::OwnedJsonb;
// Array overlap
let arr1 = r#"[1, 2, 3]"#.parse::<OwnedJsonb>().unwrap();
let arr2 = r#"[3, 4, 5]"#.parse::<OwnedJsonb>().unwrap();
assert!(arr1.as_raw().array_overlap(&arr2.as_raw()).unwrap()); // True because of '3'
let arr1 = r#"[1, 2]"#.parse::<OwnedJsonb>().unwrap();
let arr2 = r#"[3, 4]"#.parse::<OwnedJsonb>().unwrap();
assert!(!arr1.as_raw().array_overlap(&arr2.as_raw()).unwrap()); // False, no common elements
let arr1 = r#"[1, 2, 2]"#.parse::<OwnedJsonb>().unwrap();
let arr2 = r#"[2, 3]"#.parse::<OwnedJsonb>().unwrap();
assert!(arr1.as_raw().array_overlap(&arr2.as_raw()).unwrap()); // True, '2' is common
// Object/scalar overlap (requires complete equality for true)
let obj1 = r#"{"a": 1}"#.parse::<OwnedJsonb>().unwrap();
let obj2 = r#"{"a": 1}"#.parse::<OwnedJsonb>().unwrap();
assert!(obj1.as_raw().array_overlap(&obj2.as_raw()).unwrap()); // True, completely equal
let obj1 = r#"{"a": 1}"#.parse::<OwnedJsonb>().unwrap();
let obj2 = r#"{"a": 2}"#.parse::<OwnedJsonb>().unwrap();
assert!(!obj1.as_raw().array_overlap(&obj2.as_raw()).unwrap()); // False, not equal
let scalar1 = "1".parse::<OwnedJsonb>().unwrap();
let scalar2 = "1".parse::<OwnedJsonb>().unwrap();
assert!(scalar1.as_raw().array_overlap(&scalar2.as_raw()).unwrap()); // True, equal
let scalar1 = "1".parse::<OwnedJsonb>().unwrap();
let scalar2 = "2".parse::<OwnedJsonb>().unwrap();
assert!(!scalar1.as_raw().array_overlap(&scalar2.as_raw()).unwrap()); // False, not equal
// Invalid input
let invalid_jsonb = OwnedJsonb::new(vec![1, 2, 3, 4]);
let invalid_raw_jsonb = invalid_jsonb.as_raw();
let result = invalid_raw_jsonb.array_overlap(&arr1.as_raw());
assert!(result.is_err()); // Returns an error
Sourcepub fn array_insert(
&self,
pos: i32,
new_val: &RawJsonb<'_>,
) -> Result<OwnedJsonb, Error>
pub fn array_insert( &self, pos: i32, new_val: &RawJsonb<'_>, ) -> Result<OwnedJsonb, Error>
Inserts a new element into a JSONB array at the specified position.
This function inserts the new_val
into the JSONB array at the position specified by pos
.
The pos
parameter can be positive or negative:
- Positive index: 0-based index from the beginning of the array.
- Negative index: 1-based index from the end of the array (e.g., -1 refers to the last element).
If pos
is less than 0, the element is inserted at the beginning of the array.
If pos
is greater than or equal to the length of the array, the element is appended to the end.
If the input is an object or scalar, it’s treated as a single element array.
§Arguments
self
- The JSONB array.pos
- The position at which to insert the new element (positive or negative index).new_val
- The new JSONB element to insert.
§Returns
Ok(OwnedJsonb)
- The modified JSONB array with the new element inserted.Err(Error)
- If any of the input JSONB data is invalid.
§Examples
use jsonb::OwnedJsonb;
let arr_jsonb = "[1, 2, 3]".parse::<OwnedJsonb>().unwrap();
let raw_jsonb = arr_jsonb.as_raw();
let new_jsonb = "4".parse::<OwnedJsonb>().unwrap();
let new_raw_jsonb = new_jsonb.as_raw();
// Insert at index 1
let inserted = raw_jsonb.array_insert(1, &new_raw_jsonb).unwrap();
assert_eq!(inserted.to_string(), "[1,4,2,3]");
// Insert at the beginning (pos = 0)
let new_raw_jsonb = new_jsonb.as_raw();
let inserted = raw_jsonb.array_insert(0, &new_raw_jsonb).unwrap();
assert_eq!(inserted.to_string(), "[4,1,2,3]");
// Insert at the end (pos >= length)
let new_raw_jsonb = new_jsonb.as_raw();
let inserted = raw_jsonb.array_insert(10, &new_raw_jsonb).unwrap();
assert_eq!(inserted.to_string(), "[1,2,3,4]");
// Insert into an object
let obj_jsonb = r#"{"a": 1}"#.parse::<OwnedJsonb>().unwrap();
let raw_jsonb = obj_jsonb.as_raw();
let new_jsonb = "2".parse::<OwnedJsonb>().unwrap();
let new_raw_jsonb = new_jsonb.as_raw();
let inserted = raw_jsonb.array_insert(0, &new_raw_jsonb);
assert_eq!(inserted.unwrap().to_string(), r#"[2,{"a":1}]"#);
// Insert into a scalar
let scalar_jsonb = "1".parse::<OwnedJsonb>().unwrap();
let raw_jsonb = scalar_jsonb.as_raw();
let new_jsonb = "2".parse::<OwnedJsonb>().unwrap();
let new_raw_jsonb = new_jsonb.as_raw();
let inserted = raw_jsonb.array_insert(0, &new_raw_jsonb);
assert_eq!(inserted.unwrap().to_string(), "[2,1]");
Source§impl RawJsonb<'_>
impl RawJsonb<'_>
Sourcepub fn object_keys(&self) -> Result<Option<OwnedJsonb>, Error>
pub fn object_keys(&self) -> Result<Option<OwnedJsonb>, Error>
Returns an OwnedJsonb
array containing the keys of the JSONB object.
If the JSONB value is an object, this function returns a new OwnedJsonb
array containing the keys of the object as string values.
The order of the keys in the returned array is the same as their order in the original object.
If the JSONB value is not an object (e.g., it’s an array or a scalar), this function returns None
.
§Arguments
self
- The JSONB value.
§Returns
Ok(Some(OwnedJsonb))
- AnOwnedJsonb
representing the array of keys if the input is an object.Ok(None)
- If the input is not an object.Err(Error)
- If the input JSONB data is invalid.
§Examples
use jsonb::OwnedJsonb;
// Object keys
let obj_jsonb = r#"{"a": 1, "b": 2, "c": 3}"#.parse::<OwnedJsonb>().unwrap();
let raw_jsonb = obj_jsonb.as_raw();
let keys_result = raw_jsonb.object_keys();
assert!(keys_result.is_ok());
let keys_jsonb = keys_result.unwrap();
assert_eq!(
keys_jsonb.as_ref().map(|k| k.to_string()),
Some(r#"["a","b","c"]"#.to_string())
);
// Array - returns None
let arr_jsonb = "[1, 2, 3]".parse::<OwnedJsonb>().unwrap();
let raw_jsonb = arr_jsonb.as_raw();
let keys_result = raw_jsonb.object_keys();
assert!(keys_result.is_ok());
assert!(keys_result.unwrap().is_none());
// Scalar - returns None
let scalar_jsonb = "1".parse::<OwnedJsonb>().unwrap();
let raw_jsonb = scalar_jsonb.as_raw();
let keys_result = raw_jsonb.object_keys();
assert!(keys_result.is_ok());
assert!(keys_result.unwrap().is_none());
Sourcepub fn object_each(&self) -> Result<Option<Vec<(String, OwnedJsonb)>>, Error>
pub fn object_each(&self) -> Result<Option<Vec<(String, OwnedJsonb)>>, Error>
Iterates over the key-value pairs of a JSONB object.
If the JSONB value is an object, this function returns a vector of tuples, where each tuple contains
the key (as a String
) and the value (as an OwnedJsonb
) of a key-value pair.
The order of the key-value pairs in the returned vector is the same as their order in the original object.
If the JSONB value is not an object (e.g., it’s an array or a scalar), this function returns None
.
§Arguments
self
- The JSONB value.
§Returns
Ok(Some(Vec<(String, OwnedJsonb)>))
- A vector of tuples representing the key-value pairs if the input is an object.Ok(None)
- If the input is not an object.Err(Error)
- If the input JSONB data is invalid.
§Examples
use jsonb::OwnedJsonb;
// Object iteration
let obj_jsonb = r#"{"a": 1, "b": "hello", "c": [1, 2]}"#.parse::<OwnedJsonb>().unwrap();
let raw_jsonb = obj_jsonb.as_raw();
let items_result = raw_jsonb.object_each();
assert!(items_result.is_ok());
let items = items_result.unwrap().unwrap();
assert_eq!(items.len(), 3);
assert_eq!(items[0].0, "a");
assert_eq!(items[0].1.to_string(), "1");
assert_eq!(items[1].0, "b");
assert_eq!(items[1].1.to_string(), r#""hello""#);
assert_eq!(items[2].0, "c");
assert_eq!(items[2].1.to_string(), r#"[1,2]"#);
// Array - returns None
let arr_jsonb = "[1, 2, 3]".parse::<OwnedJsonb>().unwrap();
let raw_jsonb = arr_jsonb.as_raw();
let items_result = raw_jsonb.object_each();
assert!(items_result.is_ok());
assert!(items_result.unwrap().is_none());
// Scalar - returns None
let scalar_jsonb = "1".parse::<OwnedJsonb>().unwrap();
let raw_jsonb = scalar_jsonb.as_raw();
let items_result = raw_jsonb.object_each();
assert!(items_result.is_ok());
assert!(items_result.unwrap().is_none());
Sourcepub fn object_insert(
&self,
new_key: &str,
new_val: &RawJsonb<'_>,
update_flag: bool,
) -> Result<OwnedJsonb, Error>
pub fn object_insert( &self, new_key: &str, new_val: &RawJsonb<'_>, update_flag: bool, ) -> Result<OwnedJsonb, Error>
Inserts or updates a key-value pair in a JSONB object.
This function inserts a new key-value pair into a JSONB object or updates an existing key-value pair if the key already exists.
The behavior is controlled by the update_flag
:
update_flag = true
: If the key already exists, its value is updated withnew_val
. If the key does not exist, it is inserted.update_flag = false
: If the key already exists, an error (Error::ObjectDuplicateKey
) is returned. If the key does not exist, it is inserted.
The input JSONB value must be an object; otherwise, an error (Error::InvalidObject
) is returned.
§Arguments
self
- The JSONB object.new_key
- The key to insert or update.new_val
- The new JSONB value.update_flag
- A boolean indicating whether to update an existing key (true) or fail if a duplicate key is found (false).
§Returns
Ok(OwnedJsonb)
- The modified JSONB object.Err(Error)
- If the input is not a JSONB object, ifupdate_flag
is false and the key already exists, or if the JSONB data is invalid.
§Examples
use jsonb::OwnedJsonb;
// Inserting a new key-value pair
let obj_jsonb = r#"{"a": 1}"#.parse::<OwnedJsonb>().unwrap();
let raw_jsonb = obj_jsonb.as_raw();
let new_jsonb = "2".parse::<OwnedJsonb>().unwrap();
let new_raw_jsonb = new_jsonb.as_raw();
let inserted = raw_jsonb.object_insert("b", &new_raw_jsonb, false).unwrap();
assert_eq!(inserted.to_string(), r#"{"a":1,"b":2}"#);
// Updating an existing key-value pair
let new_jsonb = r#"3"#.parse::<OwnedJsonb>().unwrap();
let new_raw_jsonb = new_jsonb.as_raw();
let updated = inserted
.as_raw()
.object_insert("b", &new_raw_jsonb, true)
.unwrap();
assert_eq!(updated.to_string(), r#"{"a":1,"b":3}"#);
// Attempting to insert a duplicate key without update
let result = raw_jsonb.object_insert("a", &new_raw_jsonb, false);
assert!(result.is_err()); // Returns an error because key "a" already exists
// Invalid JSONB input
let invalid_jsonb = OwnedJsonb::new(vec![1, 2, 3, 4]);
let invalid_raw_jsonb = invalid_jsonb.as_raw();
let new_raw_jsonb = new_jsonb.as_raw();
let result = invalid_raw_jsonb.object_insert("a", &new_raw_jsonb, false);
assert!(result.is_err()); // Returns an error due to invalid JSONB data
// Inserting into a non-object
let arr_jsonb = "[1,2,3]".parse::<OwnedJsonb>().unwrap();
let arr_raw_jsonb = invalid_jsonb.as_raw();
let new_raw_jsonb = new_jsonb.as_raw();
let result = arr_raw_jsonb.object_insert("a", &new_raw_jsonb, false);
assert!(result.is_err()); // Returns an error because input is not a JSONB object
Sourcepub fn object_delete(&self, keys: &BTreeSet<&str>) -> Result<OwnedJsonb, Error>
pub fn object_delete(&self, keys: &BTreeSet<&str>) -> Result<OwnedJsonb, Error>
Deletes key-value pairs from a JSONB object based on a set of keys.
This function removes key-value pairs from a JSONB object where the keys are present in the provided keys
set. The key comparison is case-sensitive.
If the input JSONB value is not an object, an error (Error::InvalidObject
) is returned.
§Arguments
self
- The JSONB object.keys
- A set of keys to delete.
§Returns
Ok(OwnedJsonb)
- A new JSONB object with the specified keys removed.Err(Error)
- If the input JSONB value is not an object, or if the JSONB data is invalid.
§Examples
use std::collections::BTreeSet;
use jsonb::OwnedJsonb;
let obj_jsonb = r#"{"a": 1, "b": "hello", "c": 3}"#.parse::<OwnedJsonb>().unwrap();
let raw_jsonb = obj_jsonb.as_raw();
// Delete keys "a" and "c"
let keys_to_delete: BTreeSet<&str> = ["a", "c"].into_iter().collect();
let deleted = raw_jsonb.object_delete(&keys_to_delete).unwrap();
assert_eq!(deleted.to_string(), r#"{"b":"hello"}"#);
// Delete a non-existent key
let keys_to_delete: BTreeSet<&str> = ["x"].into_iter().collect();
let deleted = raw_jsonb.object_delete(&keys_to_delete).unwrap();
assert_eq!(deleted.to_string(), r#"{"a":1,"b":"hello","c":3}"#); // Original object returned
// Attempting to delete from a non-object
let arr_jsonb = "[1, 2, 3]".parse::<OwnedJsonb>().unwrap();
let result = arr_jsonb.as_raw().object_delete(&keys_to_delete);
assert!(result.is_err()); // Returns an error
// Invalid JSONB data
let invalid_jsonb = OwnedJsonb::new(vec![1, 2, 3, 4]);
let invalid_raw_jsonb = invalid_jsonb.as_raw();
let result = invalid_raw_jsonb.object_delete(&keys_to_delete);
assert!(result.is_err()); // Returns an error
Sourcepub fn object_pick(&self, keys: &BTreeSet<&str>) -> Result<OwnedJsonb, Error>
pub fn object_pick(&self, keys: &BTreeSet<&str>) -> Result<OwnedJsonb, Error>
Creates a new JSONB object containing only the specified keys from the original object.
This function selects a subset of key-value pairs from a JSONB object based on the provided keys
set.
Only key-value pairs where the key is present in the keys
set are included in the resulting object. The key comparison is case-sensitive.
If the input JSONB value is not an object, an error (Error::InvalidObject
) is returned.
§Arguments
self
- The JSONB object.keys
- A set of keys to select.
§Returns
Ok(OwnedJsonb)
- A new JSONB object containing only the key-value pairs specified by thekeys
set.Err(Error)
- If the input JSONB value is not an object, or if the JSONB data is invalid.
§Examples
use std::collections::BTreeSet;
use jsonb::OwnedJsonb;
let obj_jsonb = r#"{"a": 1, "b": "hello", "c": 3}"#.parse::<OwnedJsonb>().unwrap();
let raw_jsonb = obj_jsonb.as_raw();
// Pick keys "a" and "c"
let keys_to_pick: BTreeSet<&str> = ["a", "c"].into_iter().collect();
let picked = raw_jsonb.object_pick(&keys_to_pick).unwrap();
assert_eq!(picked.to_string(), r#"{"a":1,"c":3}"#);
// Pick a non-existent key
let keys_to_pick: BTreeSet<&str> = ["x"].into_iter().collect();
let picked = raw_jsonb.object_pick(&keys_to_pick).unwrap();
assert_eq!(picked.to_string(), "{}"); // Empty object returned
// Attempting to pick from a non-object
let arr_jsonb = "[1, 2, 3]".parse::<OwnedJsonb>().unwrap();
let result = arr_jsonb.as_raw().object_pick(&keys_to_pick);
assert!(result.is_err()); // Returns an error
// Invalid JSONB data
let invalid_jsonb = OwnedJsonb::new(vec![1, 2, 3, 4]);
let invalid_raw_jsonb = invalid_jsonb.as_raw();
let result = invalid_raw_jsonb.object_pick(&keys_to_pick);
assert!(result.is_err()); // Returns an error
Source§impl RawJsonb<'_>
impl RawJsonb<'_>
Sourcepub fn type_of(&self) -> Result<&'static str, Error>
pub fn type_of(&self) -> Result<&'static str, Error>
Determines the type of a JSONB value.
This function returns a string representation of the JSONB value’s type. The possible return values are:
"null"
"boolean"
"number"
"string"
"array"
"object"
"decimal"
"binary"
"date"
"timestamp"
"timestamp_tz"
"interval"
§Arguments
self
- The JSONB value.
§Returns
Ok(&'static str)
- A string slice representing the type of the JSONB value.Err(Error)
- If an error occurred during decoding (e.g., invalid JSONB data).
§Examples
use jsonb::OwnedJsonb;
// Type checking
let arr_jsonb = "[1, 2, 3]".parse::<OwnedJsonb>().unwrap();
let raw_jsonb = arr_jsonb.as_raw();
assert_eq!(raw_jsonb.type_of().unwrap(), "ARRAY");
let obj_jsonb = r#"{"a": 1}"#.parse::<OwnedJsonb>().unwrap();
let raw_jsonb = obj_jsonb.as_raw();
assert_eq!(raw_jsonb.type_of().unwrap(), "OBJECT");
let num_jsonb = "1".parse::<OwnedJsonb>().unwrap();
let raw_jsonb = num_jsonb.as_raw();
assert_eq!(raw_jsonb.type_of().unwrap(), "INTEGER");
let string_jsonb = r#""hello""#.parse::<OwnedJsonb>().unwrap();
let raw_jsonb = string_jsonb.as_raw();
assert_eq!(raw_jsonb.type_of().unwrap(), "STRING");
let bool_jsonb = "true".parse::<OwnedJsonb>().unwrap();
let raw_jsonb = bool_jsonb.as_raw();
assert_eq!(raw_jsonb.type_of().unwrap(), "BOOLEAN");
let null_jsonb = "null".parse::<OwnedJsonb>().unwrap();
let raw_jsonb = null_jsonb.as_raw();
assert_eq!(raw_jsonb.type_of().unwrap(), "NULL_VALUE");
Sourcepub fn contains(&self, other: &RawJsonb<'_>) -> Result<bool, Error>
pub fn contains(&self, other: &RawJsonb<'_>) -> Result<bool, Error>
Checks if the JSONB value contains other JSONB value.
Containment is defined as follows:
- Scalar values: Two scalar values are considered equal if their byte representations are identical.
- Objects: The self object contains the other object if all key-value pairs in the other object exist in the self object with the same values. The self object may have additional key-value pairs.
- Arrays: The self array contains the other array if, for every element in the other array, there exists an identical element in the self array. The self array may have additional elements. Note that order does not matter for containment, and duplicate elements are handled correctly. Nested arrays are also supported.
§Arguments
self
- The self JSONB value.other
- The other JSONB value.
§Returns
Ok(true)
if the self JSONB value contains the other JSONB value.Ok(false)
if the self JSONB value does not contain the other JSONB value.Err(Error)
if an error occurred during decoding.
§Examples
use jsonb::OwnedJsonb;
// Example 1: Array containment
let left_jsonb = "[1, 2, 3]".parse::<OwnedJsonb>().unwrap();
let left_raw = left_jsonb.as_raw();
let right_jsonb = "[3, 1]".parse::<OwnedJsonb>().unwrap();
let right_raw = right_jsonb.as_raw();
assert!(left_raw.contains(&right_raw).unwrap());
// Example 2: Object containment with nested structures
let left_jsonb = r#"{"a": 1, "b": {"c": 2, "d": 3}}"#.parse::<OwnedJsonb>().unwrap();
let left_raw = left_jsonb.as_raw();
let right_jsonb = r#"{"b": {"c": 2}}"#.parse::<OwnedJsonb>().unwrap();
let right_raw = right_jsonb.as_raw();
assert!(left_raw.contains(&right_raw).unwrap());
Sourcepub fn traverse_check_string(
&self,
func: impl Fn(&[u8]) -> bool,
) -> Result<bool, Error>
pub fn traverse_check_string( &self, func: impl Fn(&[u8]) -> bool, ) -> Result<bool, Error>
Traverses the JSONB value and checks string values against a provided function.
This function recursively traverses the JSONB value, visiting all string elements.
For each string element, it calls the provided func
. If func
returns true
for any string element,
the traversal stops, and the function returns Ok(true)
. If func
returns false
for all string elements,
the traversal completes, and the function returns Ok(false)
.
This function is useful for efficiently searching for a specific string within a potentially complex JSONB structure without having to manually traverse the entire structure.
§Arguments
func
- A function that takes a byte slice (&[u8]
) representing a string value and returns a boolean indicating whether the string satisfies a certain condition.
§Returns
Ok(true)
- Iffunc
returnstrue
for any string element encountered during traversal.Ok(false)
- Iffunc
returnsfalse
for all string elements.Err(Error)
- If an error occurred during decoding (e.g., invalid JSONB data).
§Examples
use jsonb::OwnedJsonb;
let jsonb_value = r#"{"a": "hello", "b": [1, "world", {"c": "rust"}]}"#
.parse::<OwnedJsonb>()
.unwrap();
let raw_jsonb = jsonb_value.as_raw();
// Check if any string contains "rust"
let contains_rust = raw_jsonb
.traverse_check_string(|s| s.eq("rust".as_bytes()))
.unwrap();
assert!(contains_rust);
// Check if any string contains "xyz"
let contains_xyz = raw_jsonb
.traverse_check_string(|s| s.eq("xyz".as_bytes()))
.unwrap();
assert!(!contains_xyz);
// Check if any string is longer than 5 characters
let long_string = raw_jsonb.traverse_check_string(|s| s.len() > 5).unwrap();
assert!(!long_string);
// Example with an array of strings
let jsonb_value = r#"["hello", "world", "rust"]"#.parse::<OwnedJsonb>().unwrap();
let raw_jsonb = jsonb_value.as_raw();
let contains_rust = raw_jsonb
.traverse_check_string(|s| s.eq("rust".as_bytes()))
.unwrap();
assert!(contains_rust);
Sourcepub fn concat(&self, other: &RawJsonb<'_>) -> Result<OwnedJsonb, Error>
pub fn concat(&self, other: &RawJsonb<'_>) -> Result<OwnedJsonb, Error>
Concatenates two JSONB values.
This function concatenates the self
JSONB value with the other
JSONB value.
The concatenation behavior depends on the types of the input values:
- Object + Object: Merges the two objects. If there are duplicate keys, the keys from the
other
object will overwrite the keys from theself
object. - Array + Array: Appends the elements of the
other
array to theself
array. - Object/Scalar + Array: Creates a new array containing the
self
value (as a single element) followed by the elements of theother
array. - Array + Object/Scalar: Creates a new array containing the elements of the
self
array followed by theother
value (as a single element). - Object/Scalar + Object/Scalar: Creates a new array containing the
self
andother
(as a single element).
§Arguments
self
- The first JSONB value.other
- The second JSONB value.
§Returns
Ok(OwnedJsonb)
- The concatenated JSONB value.Err(Error)
- If the input JSONB values are invalid, or if an unsupported concatenation is attempted.
§Examples
use jsonb::OwnedJsonb;
// Object + Object
let obj1 = r#"{"a": 1, "b": 2}"#.parse::<OwnedJsonb>().unwrap();
let obj2 = r#"{"b": 3, "c": 4}"#.parse::<OwnedJsonb>().unwrap();
let concatenated = obj1.as_raw().concat(&obj2.as_raw()).unwrap();
assert_eq!(concatenated.to_string(), r#"{"a":1,"b":3,"c":4}"#); // "b" is overwritten
// Array + Array
let arr1 = "[1, 2]".parse::<OwnedJsonb>().unwrap();
let arr2 = "[3, 4]".parse::<OwnedJsonb>().unwrap();
let concatenated = arr1.as_raw().concat(&arr2.as_raw()).unwrap();
assert_eq!(concatenated.to_string(), "[1,2,3,4]");
// Object + Array
let obj = r#"{"a": 1}"#.parse::<OwnedJsonb>().unwrap();
let arr = "[2, 3]".parse::<OwnedJsonb>().unwrap();
let concatenated = obj.as_raw().concat(&arr.as_raw()).unwrap();
assert_eq!(concatenated.to_string(), r#"[{"a":1},2,3]"#);
// Scalar + Array
let scalar = "1".parse::<OwnedJsonb>().unwrap();
let arr = "[2, 3]".parse::<OwnedJsonb>().unwrap();
let concatenated = scalar.as_raw().concat(&arr.as_raw()).unwrap();
assert_eq!(concatenated.to_string(), "[1,2,3]");
// Scalar + Scalar
let scalar1 = "1".parse::<OwnedJsonb>().unwrap();
let scalar2 = "2".parse::<OwnedJsonb>().unwrap();
let concatenated = scalar1.as_raw().concat(&scalar2.as_raw()).unwrap();
assert_eq!(concatenated.to_string(), "[1,2]");
Sourcepub fn strip_nulls(&self) -> Result<OwnedJsonb, Error>
pub fn strip_nulls(&self) -> Result<OwnedJsonb, Error>
Recursively reomves all object key-value pairs that have null values from a JSONB object.
Note: null values in the JSONB array are not reomved.
§Arguments
self
- The first JSONB value.
§Returns
Ok(OwnedJsonb)
- The JSONB value with nulls removed.Err(Error)
- If the input JSONB value is invalid.
§Examples
use jsonb::OwnedJsonb;
// Object with nulls
let obj_with_nulls = r#"{"a": 1, "b": null, "c": 3}"#.parse::<OwnedJsonb>().unwrap();
let stripped = obj_with_nulls.as_raw().strip_nulls().unwrap();
assert_eq!(stripped.to_string(), r#"{"a":1,"c":3}"#);
// Nested structures
let nested = r#"{"a": [1, null, {"b": null, "c": 2}]}"#.parse::<OwnedJsonb>().unwrap();
let stripped = nested.as_raw().strip_nulls().unwrap();
assert_eq!(stripped.to_string(), r#"{"a":[1,null,{"c":2}]}"#);
// Array with nulls
let arr_with_nulls = r#"[1, null, 3]"#.parse::<OwnedJsonb>().unwrap();
let stripped = arr_with_nulls.as_raw().strip_nulls().unwrap();
assert_eq!(stripped.to_string(), r#"[1,null,3]"#); // Remains unchanged
// Scalar null
let null_scalar = "null".parse::<OwnedJsonb>().unwrap();
let stripped = null_scalar.as_raw().strip_nulls().unwrap();
assert_eq!(stripped.to_string(), "null"); // Remains unchanged
Sourcepub fn convert_to_comparable(&self) -> Vec<u8> ⓘ
pub fn convert_to_comparable(&self) -> Vec<u8> ⓘ
Converts a RawJsonb value into a comparable binary representation.
This function transforms the JSONB value into a new binary format designed for efficient comparison.
The resulting binary data can be directly compared using byte-wise operations to determine the relative order of two JSONB values.
The original JSONB data structure is flattened into a linear representation, and different data types are encoded in a way that enables direct comparison.
The compare rules are the same as the PartialOrd
trait.
Scalar Null > Array > Object > Other Scalars(String > Number > Boolean).
Important: The resulting byte array is not a valid JSONB format; it’s specifically designed for comparison purposes and should not be interpreted as standard JSONB data.
§Arguments
self
- The RawJsonb value to convert.
§Returns
A Vec<u8>
representing the comparable binary form of the JSONB data.
§Examples
use jsonb::OwnedJsonb;
let json1 = r#"{"a":1,"b":"hello"}"#.parse::<OwnedJsonb>().unwrap();
let json2 = r#"{"a":1,"b":"world"}"#.parse::<OwnedJsonb>().unwrap();
let json3 = r#"{"a":2,"b":"hello"}"#.parse::<OwnedJsonb>().unwrap();
let json4 = r#"{"a":1,"b":[1,2,3]}"#.parse::<OwnedJsonb>().unwrap();
let json5 = r#"{"a":1,"b":[1,2]}"#.parse::<OwnedJsonb>().unwrap();
let json6 = "[1,2,3]".parse::<OwnedJsonb>().unwrap();
let json7 = "[1,2]".parse::<OwnedJsonb>().unwrap();
let json8 = "1".parse::<OwnedJsonb>().unwrap();
let json9 = "2".parse::<OwnedJsonb>().unwrap();
let comparable1 = json1.as_raw().convert_to_comparable();
let comparable2 = json2.as_raw().convert_to_comparable();
let comparable3 = json3.as_raw().convert_to_comparable();
let comparable4 = json4.as_raw().convert_to_comparable();
let comparable5 = json5.as_raw().convert_to_comparable();
let comparable6 = json6.as_raw().convert_to_comparable();
let comparable7 = json7.as_raw().convert_to_comparable();
let comparable8 = json8.as_raw().convert_to_comparable();
let comparable9 = json9.as_raw().convert_to_comparable();
assert!(comparable1 < comparable2);
assert!(comparable1 < comparable3);
assert!(comparable1 < comparable4);
assert!(comparable4 > comparable5);
assert!(comparable6 > comparable7);
assert!(comparable8 < comparable9);
Source§impl RawJsonb<'_>
impl RawJsonb<'_>
Sourcepub fn get_by_index(&self, index: usize) -> Result<Option<OwnedJsonb>, Error>
pub fn get_by_index(&self, index: usize) -> Result<Option<OwnedJsonb>, Error>
Gets the element at the specified index in a JSONB array.
If the JSONB value is an array, this function returns the element at the given index
as an OwnedJsonb
.
If the index
is out of bounds, it returns Ok(None)
.
If the JSONB value is not an array (e.g., it’s an object or a scalar), this function also returns Ok(None)
.
§Arguments
self
- The JSONB value.index
- The index of the desired element.
§Returns
Ok(Some(OwnedJsonb))
- The element at the specified index as anOwnedJsonb
if the input is an array and the index is valid.Ok(None)
- If the input is not an array, or if the index is out of bounds.Err(Error)
- If an error occurred during decoding (e.g., invalid JSONB data).
§Examples
use jsonb::OwnedJsonb;
let arr_jsonb = r#"[1, "hello", {"a": 1}]"#.parse::<OwnedJsonb>().unwrap();
let raw_jsonb = arr_jsonb.as_raw();
let element0 = raw_jsonb.get_by_index(0).unwrap();
assert_eq!(element0.unwrap().to_string(), "1");
let element1 = raw_jsonb.get_by_index(1).unwrap();
assert_eq!(element1.unwrap().to_string(), r#""hello""#);
let element2 = raw_jsonb.get_by_index(2).unwrap();
assert_eq!(element2.unwrap().to_string(), r#"{"a":1}"#);
let element3 = raw_jsonb.get_by_index(3).unwrap();
assert!(element3.is_none()); // Index out of bounds
let obj_jsonb = r#"{"a": 1}"#.parse::<OwnedJsonb>().unwrap();
let raw_jsonb = obj_jsonb.as_raw();
let element = raw_jsonb.get_by_index(0).unwrap();
assert!(element.is_none()); // Not an array
Sourcepub fn get_by_name(
&self,
name: &str,
ignore_case: bool,
) -> Result<Option<OwnedJsonb>, Error>
pub fn get_by_name( &self, name: &str, ignore_case: bool, ) -> Result<Option<OwnedJsonb>, Error>
Gets the value associated with a given key in a JSONB object.
If the JSONB value is an object, this function searches for a key matching the provided name
and returns the associated value as an OwnedJsonb
.
The ignore_case
parameter controls whether the key search is case-sensitive.
If the key is not found, it returns Ok(None)
.
If the JSONB value is not an object (e.g., it’s an array or a scalar), this function also returns Ok(None)
.
§Arguments
self
- The JSONB value.name
- The key to search for.ignore_case
- Whether the key search should be case-insensitive.
§Returns
Ok(Some(OwnedJsonb))
- The value associated with the key as anOwnedJsonb
, if the input is an object and the key is found.Ok(None)
- If the input is not an object, or if the key is not found.Err(Error)
- If an error occurred during decoding (e.g., invalid JSONB data).
§Examples
use jsonb::OwnedJsonb;
let obj_jsonb = r#"{"a": 1, "b": "hello", "c": [1, 2]}"#.parse::<OwnedJsonb>().unwrap();
let raw_jsonb = obj_jsonb.as_raw();
let value_a = raw_jsonb.get_by_name("a", false).unwrap();
assert_eq!(value_a.unwrap().to_string(), "1");
let value_b = raw_jsonb.get_by_name("b", false).unwrap();
assert_eq!(value_b.unwrap().to_string(), r#""hello""#);
let value_c = raw_jsonb.get_by_name("c", false).unwrap();
assert_eq!(value_c.unwrap().to_string(), "[1,2]");
let value_d = raw_jsonb.get_by_name("d", false).unwrap();
assert!(value_d.is_none()); // Key not found
// Case-insensitive search
let value_a_case_insensitive = raw_jsonb.get_by_name("A", true).unwrap();
assert_eq!(value_a_case_insensitive.unwrap().to_string(), "1");
let arr_jsonb = "[1, 2, 3]".parse::<OwnedJsonb>().unwrap();
let raw_jsonb = arr_jsonb.as_raw();
let value = raw_jsonb.get_by_name("a", false).unwrap();
assert!(value.is_none()); // Not an object
Sourcepub fn get_by_keypath<'a, I: Iterator<Item = &'a KeyPath<'a>>>(
&self,
keypaths: I,
) -> Result<Option<OwnedJsonb>, Error>
pub fn get_by_keypath<'a, I: Iterator<Item = &'a KeyPath<'a>>>( &self, keypaths: I, ) -> Result<Option<OwnedJsonb>, Error>
Gets the value at the specified key path in a JSONB value.
This function traverses the JSONB value according to the provided key path
and returns the value at the final path element as an OwnedJsonb
.
The key path is an iterator of KeyPath
elements, which can be
either named keys (for objects) or array indices.
If any element in the key path does not exist or if the type of the current value
does not match the key path element (e.g., trying to access a named key in an array),
the function returns Ok(None)
.
If the key path is empty, the function returns the original RawJsonb
value wrapped in Some
.
§Arguments
self
- The JSONB value.keypaths
- An iterator ofKeyPath
elements representing the path to traverse.
§Returns
Ok(Some(OwnedJsonb))
- The value at the specified key path as anOwnedJsonb
, if found.Ok(None)
- If the key path is invalid or leads to a non-existent value.Err(Error)
- If an error occurred during decoding (e.g., invalid JSONB data).
§Examples
use std::borrow::Cow;
use jsonb::{keypath::KeyPath, OwnedJsonb, RawJsonb};
let jsonb_value = r#"{"a": {"b": [1, 2, 3], "c": "hello"}, "d": [4, 5]}"#.parse::<OwnedJsonb>().unwrap();
let raw_jsonb = jsonb_value.as_raw();
// Accessing nested values
let path = [KeyPath::Name(Cow::Borrowed("a")), KeyPath::Name(Cow::Borrowed("b")), KeyPath::Index(1)];
let value = raw_jsonb.get_by_keypath(path.iter()).unwrap();
assert_eq!(value.unwrap().to_string(), "2");
let path = [KeyPath::Name(Cow::Borrowed("a")), KeyPath::Name(Cow::Borrowed("c"))];
let value = raw_jsonb.get_by_keypath(path.iter()).unwrap();
assert_eq!(value.unwrap().to_string(), r#""hello""#);
let path = [KeyPath::Name(Cow::Borrowed("d")), KeyPath::Index(0)];
let value = raw_jsonb.get_by_keypath(path.iter()).unwrap();
assert_eq!(value.unwrap().to_string(), "4");
// Invalid key path
let path = [KeyPath::Name(Cow::Borrowed("a")), KeyPath::Name(Cow::Borrowed("x"))]; // "x" doesn't exist
let value = raw_jsonb.get_by_keypath(path.iter()).unwrap();
assert!(value.is_none());
let path = [KeyPath::Name(Cow::Borrowed("a")), KeyPath::Index(0)]; // "a" is an object, not an array
let value = raw_jsonb.get_by_keypath(path.iter()).unwrap();
assert!(value.is_none());
// Empty key path - returns the original value
let value = raw_jsonb.get_by_keypath([].iter()).unwrap();
assert_eq!(value.unwrap().to_string(), r#"{"a":{"b":[1,2,3],"c":"hello"},"d":[4,5]}"#);
// KeyPath with quoted name
let jsonb_value = r#"{"a b": 1}"#.parse::<OwnedJsonb>().unwrap();
let raw_jsonb = jsonb_value.as_raw();
let path = [KeyPath::QuotedName(Cow::Borrowed("a b"))];
let value = raw_jsonb.get_by_keypath(path.iter()).unwrap();
assert_eq!(value.unwrap().to_string(), r#"1"#);
Sourcepub fn select_by_path<'a>(
&self,
json_path: &'a JsonPath<'a>,
) -> Result<Vec<OwnedJsonb>, Error>
pub fn select_by_path<'a>( &self, json_path: &'a JsonPath<'a>, ) -> Result<Vec<OwnedJsonb>, Error>
Selects elements from the RawJsonb
by the given JsonPath
.
This function returns all matching elements as a Vec<OwnedJsonb>
.
§Arguments
self
- The JSONB value.json_path
- The JSONPath expression.
§Returns
Ok(Vec<OwnedJsonb>)
- A vector containing the selectedOwnedJsonb
values.Err(Error)
- If the JSONB data is invalid or if an error occurs during path evaluation.
§Examples
use jsonb::OwnedJsonb;
use jsonb::jsonpath::parse_json_path;
let jsonb_value = r#"{"a": {"b": [1, 2, 3]}, "c": 4}"#.parse::<OwnedJsonb>().unwrap();
let raw_jsonb = jsonb_value.as_raw();
let path = parse_json_path("$.a.b[*]".as_bytes()).unwrap();
let result = raw_jsonb.select_by_path(&path).unwrap();
assert_eq!(result.len(), 3);
assert_eq!(result[0].to_string(), "1");
assert_eq!(result[1].to_string(), "2");
assert_eq!(result[2].to_string(), "3");
Sourcepub fn select_array_by_path<'a>(
&self,
json_path: &'a JsonPath<'a>,
) -> Result<OwnedJsonb, Error>
pub fn select_array_by_path<'a>( &self, json_path: &'a JsonPath<'a>, ) -> Result<OwnedJsonb, Error>
Selects elements from the RawJsonb
by the given JsonPath
and wraps them in a JSON array.
This function returns all matching elements as a single OwnedJsonb
representing a JSON array.
§Arguments
self
- The JSONB value.json_path
- The JSONPath expression.
§Returns
Ok(OwnedJsonb)
- A singleOwnedJsonb
(a JSON array) containing the selected values.Err(Error)
- If the JSONB data is invalid or if an error occurs during path evaluation.
§Examples
use jsonb::OwnedJsonb;
use jsonb::jsonpath::parse_json_path;
let jsonb_value = r#"{"a": {"b": [1, 2, 3]}, "c": 4}"#.parse::<OwnedJsonb>().unwrap();
let raw_jsonb = jsonb_value.as_raw();
let path = parse_json_path("$.a.b[*]".as_bytes()).unwrap();
let result = raw_jsonb.select_array_by_path(&path).unwrap();
assert_eq!(result.to_string(), "[1,2,3]");
Sourcepub fn select_first_by_path<'a>(
&self,
json_path: &'a JsonPath<'a>,
) -> Result<Option<OwnedJsonb>, Error>
pub fn select_first_by_path<'a>( &self, json_path: &'a JsonPath<'a>, ) -> Result<Option<OwnedJsonb>, Error>
Selects the first matching element from the RawJsonb
by the given JsonPath
.
This function returns the first matched element wrapped in Some
, or None
if no element matches the path.
§Arguments
self
- The JSONB value.json_path
- The JSONPath expression.
§Returns
Ok(Some(OwnedJsonb))
- A singleOwnedJsonb
containing the first matched value.Ok(None)
- The path does not match any values.Err(Error)
- If the JSONB data is invalid or if an error occurs during path evaluation.
§Examples
use jsonb::OwnedJsonb;
use jsonb::jsonpath::parse_json_path;
let jsonb_value = r#"{"a": [{"b": 1}, {"b": 2}], "c": 3}"#.parse::<OwnedJsonb>().unwrap();
let raw_jsonb = jsonb_value.as_raw();
let path = parse_json_path("$.a[0].b".as_bytes()).unwrap(); // Matches multiple values.
let result = raw_jsonb.select_first_by_path(&path).unwrap();
assert_eq!(result.unwrap().to_string(), "1");
let path = parse_json_path("$.d".as_bytes()).unwrap(); // No match.
let result = raw_jsonb.select_first_by_path(&path).unwrap();
assert!(result.is_none());
Sourcepub fn select_value_by_path<'a>(
&self,
json_path: &'a JsonPath<'a>,
) -> Result<Option<OwnedJsonb>, Error>
pub fn select_value_by_path<'a>( &self, json_path: &'a JsonPath<'a>, ) -> Result<Option<OwnedJsonb>, Error>
Selects a value (or an array of values) from the RawJsonb
by the given JsonPath
.
If exactly one element matches, it is returned directly (wrapped in Some
).
If multiple elements match, they are returned as a JSON array (wrapped in Some
).
If no elements match, None
is returned.
§Arguments
self
- The JSONB value.json_path
- The JSONPath expression.
§Returns
Ok(Some(OwnedJsonb))
- A singleOwnedJsonb
containing the matched values.Ok(None)
- The path does not match any values.Err(Error)
- If the JSONB data is invalid or if an error occurs during path evaluation.
§Examples
use jsonb::OwnedJsonb;
use jsonb::jsonpath::parse_json_path;
let jsonb_value = r#"{"a": [{"b": 1}, {"b": 2}], "c": 3}"#.parse::<OwnedJsonb>().unwrap();
let raw_jsonb = jsonb_value.as_raw();
let path = parse_json_path("$.c".as_bytes()).unwrap(); // Matches a single value.
let result = raw_jsonb.select_value_by_path(&path).unwrap();
assert_eq!(result.unwrap().to_string(), "3");
let path = parse_json_path("$.a[*].b".as_bytes()).unwrap(); // Matches multiple values.
let result = raw_jsonb.select_value_by_path(&path).unwrap();
assert_eq!(result.unwrap().to_string(), "[1,2]");
let path = parse_json_path("$.x".as_bytes()).unwrap(); // No match.
let result = raw_jsonb.select_value_by_path(&path).unwrap();
assert!(result.is_none());
Sourcepub fn path_exists<'a>(
&self,
json_path: &'a JsonPath<'a>,
) -> Result<bool, Error>
pub fn path_exists<'a>( &self, json_path: &'a JsonPath<'a>, ) -> Result<bool, Error>
Checks if a JSON path exists within the JSONB value.
§Arguments
self
- The JSONB value.json_path
- The JSONPath expression.
§Returns
Ok(true)
- If the JSON path exists.Ok(false)
- If the JSON path does not exist.Err(Error)
- If the JSONB data is invalid or if an error occurs during path evaluation. This could also indicate issues with thejson_path
itself.
§Examples
use jsonb::jsonpath::parse_json_path;
use jsonb::OwnedJsonb;
let jsonb_value = r#"{"a": {"b": [1, 2, 3]}, "c": 4}"#.parse::<OwnedJsonb>().unwrap();
let raw_jsonb = jsonb_value.as_raw();
// Valid paths
let path1 = parse_json_path("$.a.b[1]".as_bytes()).unwrap();
assert!(raw_jsonb.path_exists(&path1).unwrap());
let path2 = parse_json_path("$.c".as_bytes()).unwrap();
assert!(raw_jsonb.path_exists(&path2).unwrap());
// Invalid paths
let path3 = parse_json_path("$.a.x".as_bytes()).unwrap(); // "x" does not exist
assert!(!raw_jsonb.path_exists(&path3).unwrap());
Sourcepub fn path_match<'a>(
&self,
json_path: &'a JsonPath<'a>,
) -> Result<Option<bool>, Error>
pub fn path_match<'a>( &self, json_path: &'a JsonPath<'a>, ) -> Result<Option<bool>, Error>
Checks if a JSON path matches the JSONB value using a predicate.
This function checks if a given JSON Path, along with an associated predicate, matches the JSONB value. The predicate determines the conditions that the selected value(s) must satisfy for the match to be considered successful.
§Arguments
self
- The JSONB value.json_path
- The JSONPath expression with a predicate. The predicate is specified within thejson_path
using the standard JSONPath syntax. For example,$.store.book[?(@.price < 10)]
selects books with a price less than 10.
§Returns
Ok(Some(true))
- If the JSON path with its predicate matches at least one value in the JSONB data.Ok(Some(false))
- If the JSON path with its predicate does not match any values.Ok(None)
- If the JSON path is not a predicate expr or predicate result is not a boolean value.Err(Error)
- If the JSONB data is invalid or if an error occurs during path evaluation or predicate checking. This could also indicate issues with thejson_path
itself (invalid syntax, etc.).
§Examples
use jsonb::jsonpath::parse_json_path;
use jsonb::OwnedJsonb;
let jsonb_value = r#"[
{"price": 12, "title": "Book A"},
{"price": 8, "title": "Book B"},
{"price": 5, "title": "Book C"}
]"#
.parse::<OwnedJsonb>()
.unwrap();
let raw_jsonb = jsonb_value.as_raw();
// Path with predicate (select books with price < 10)
let path = parse_json_path("$[*].price < 10".as_bytes()).unwrap();
assert_eq!(raw_jsonb.path_match(&path).unwrap(), Some(true)); // True because Book B and Book C match.
// Path with predicate (select books with title "Book D")
let path = parse_json_path("$[*].title == \"Book D\"".as_bytes()).unwrap();
assert_eq!(raw_jsonb.path_match(&path).unwrap(), Some(false)); // False because no book has this title.
// Path is not a predicate expr
let path = parse_json_path("$[*].title".as_bytes()).unwrap();
assert_eq!(raw_jsonb.path_match(&path).unwrap(), None);
Sourcepub fn delete_by_index(&self, index: i32) -> Result<OwnedJsonb, Error>
pub fn delete_by_index(&self, index: i32) -> Result<OwnedJsonb, Error>
Deletes the element at the specified index from a JSONB array.
This function removes the element at the given index
from a JSONB array.
The index
can be positive or negative:
- Positive index: 0-based index from the beginning of the array.
- Negative index: 1-based index from the end of the array (e.g., -1 refers to the last element).
If the index
is out of bounds, the original JSONB array is returned unchanged.
If the input JSONB value is not an array (e.g., it’s an object or a scalar), an Error::InvalidJsonType
is returned.
Other invalid JSONB data results in an Error::InvalidJsonb
.
§Arguments
self
- The JSONB value.index
- The index of the element to delete.
§Returns
Ok(OwnedJsonb)
- The JSONB array with the element at the specified index removed, or the original array if the index is out of bounds.Err(Error)
- If the input JSONB value is not an array, or if the JSONB data is invalid.
§Examples
use jsonb::OwnedJsonb;
let arr_jsonb = r#"[1, "hello", 3, 4]"#.parse::<OwnedJsonb>().unwrap();
let raw_jsonb = arr_jsonb.as_raw();
// Delete element at index 1
let deleted = raw_jsonb.delete_by_index(1).unwrap();
assert_eq!(deleted.to_string(), "[1,3,4]");
// Delete last element using negative index
let deleted = raw_jsonb.delete_by_index(-1).unwrap();
assert_eq!(deleted.to_string(), "[1,\"hello\",3]");
// Out of bounds index (positive)
let deleted = raw_jsonb.delete_by_index(4).unwrap();
assert_eq!(deleted.to_string(), "[1,\"hello\",3,4]"); // Original array returned
// Out of bounds index (negative)
let deleted = raw_jsonb.delete_by_index(-5).unwrap();
assert_eq!(deleted.to_string(), "[1,\"hello\",3,4]"); // Original array returned
let obj_jsonb = r#"{"a": 1}"#.parse::<OwnedJsonb>().unwrap();
let raw_jsonb = obj_jsonb.as_raw();
let result = raw_jsonb.delete_by_index(0);
assert!(result.is_err()); // Error because input is not an array
Sourcepub fn delete_by_name(&self, name: &str) -> Result<OwnedJsonb, Error>
pub fn delete_by_name(&self, name: &str) -> Result<OwnedJsonb, Error>
Deletes a key-value pair from a JSONB object or an element from a JSONB array.
This function removes a key-value pair from a JSONB object if the key matches the given name
or removes an element from a JSONB array if the element is a string that matches the given name
.
- Object: If the input is an object, the key-value pair with the matching key is removed. The key comparison is case-sensitive.
- Array: If the input is an array, elements that are strings and match
name
(case-sensitive) are removed. Other array elements remain unchanged. - Invalid input: If the input JSONB value is a scalar value, an
Error::InvalidJsonType
is returned. Other invalid JSONB data results in anError::InvalidJsonb
.
§Arguments
self
- The JSONB value.name
- The key (for objects) or string value (for arrays) to match.
§Returns
Ok(OwnedJsonb)
- The modified JSONB value with the matching key-value pair or element removed.Err(Error)
- If the input JSONB value is a scalar, or if the JSONB data is invalid.
§Examples
use jsonb::OwnedJsonb;
// Deleting from an object
let obj_jsonb = r#"{"a": 1, "b": "hello", "c": 3}"#.parse::<OwnedJsonb>().unwrap();
let raw_jsonb = obj_jsonb.as_raw();
let deleted = raw_jsonb.delete_by_name("b").unwrap();
assert_eq!(deleted.to_string(), r#"{"a":1,"c":3}"#);
// Deleting from an array (string elements only)
let arr_jsonb = r#"[1, "hello", 3, "world"]"#.parse::<OwnedJsonb>().unwrap();
let raw_jsonb = arr_jsonb.as_raw();
let deleted = raw_jsonb.delete_by_name("hello").unwrap();
assert_eq!(deleted.to_string(), "[1,3,\"world\"]");
// Non-matching key in object
let deleted = raw_jsonb.delete_by_name("x").unwrap(); // "x" doesn't exist
assert_eq!(deleted.to_string(), r#"[1,"hello",3,"world"]"#); // Original array returned
// Non-matching value in array
let deleted = arr_jsonb.as_raw().delete_by_name("xyz").unwrap(); // "xyz" doesn't exist
assert_eq!(deleted.to_string(), r#"[1,"hello",3,"world"]"#); // Original array returned
// Attempting to delete from a scalar
let scalar_jsonb = "1".parse::<OwnedJsonb>().unwrap();
let raw_jsonb = scalar_jsonb.as_raw();
let result = raw_jsonb.delete_by_name("a");
assert!(result.is_err()); // Returns an error
Sourcepub fn delete_by_keypath<'a, I: Iterator<Item = &'a KeyPath<'a>>>(
&self,
keypaths: I,
) -> Result<OwnedJsonb, Error>
pub fn delete_by_keypath<'a, I: Iterator<Item = &'a KeyPath<'a>>>( &self, keypaths: I, ) -> Result<OwnedJsonb, Error>
Deletes a value from a JSONB array or object based on a key path.
This function removes a value from a JSONB array or object using a key path.
The key path is an iterator of KeyPath
elements specifying the path to the element to delete.
- Array: If the JSONB value is an array, the key path must consist of array indices (
KeyPath::Index
). A negative index counts from the end of the array (e.g., -1 is the last element). If the index is out of bounds, the original JSONB value is returned unchanged. - Object: If the JSONB value is an object, the key path can be a mix of object keys (
KeyPath::Name
orKeyPath::QuotedName
) and array indices. If any part of the path is invalid (e.g., trying to access an index in a non-array or a key in a non-object), the original JSONB value is returned unchanged. - Invalid input: If the input is neither an array nor an object, or if the JSONB data is otherwise invalid,
an error (
Error::InvalidJsonType
orError::InvalidJsonb
) is returned.
§Arguments
self
- The JSONB value.keypath
- An iterator ofKeyPath
elements specifying the path to the element to delete.
§Returns
Ok(OwnedJsonb)
- The JSONB value with the specified element deleted. Returns the original value if the keypath is invalid or leads to a non-existent value.Err(Error)
- If the input JSONB value is neither an array nor an object, or if the JSONB data is invalid.
§Examples
use std::borrow::Cow;
use jsonb::keypath::KeyPath;
use jsonb::OwnedJsonb;
// Deleting from an array
let arr_jsonb = r#"[1, 2, 3]"#.parse::<OwnedJsonb>().unwrap();
let raw_jsonb = arr_jsonb.as_raw();
let keypath = [KeyPath::Index(1)]; // Delete element at index 1
let deleted = raw_jsonb.delete_by_keypath(keypath.iter()).unwrap();
assert_eq!(deleted.to_string(), "[1,3]");
let keypath = [KeyPath::Index(-1)]; // Delete last element
let deleted = raw_jsonb.delete_by_keypath(keypath.iter()).unwrap();
assert_eq!(deleted.to_string(), "[1,2]");
// Deleting from an object
let obj_jsonb = r#"{"a": {"b": [1, 2, 3]}, "c": 4}"#.parse::<OwnedJsonb>().unwrap();
let raw_jsonb = obj_jsonb.as_raw();
let keypath = [
KeyPath::Name(Cow::Borrowed("a")),
KeyPath::Name(Cow::Borrowed("b")),
KeyPath::Index(1),
];
let deleted = raw_jsonb.delete_by_keypath(keypath.iter()).unwrap();
assert_eq!(deleted.to_string(), r#"{"a":{"b":[1,3]},"c":4}"#);
// Invalid keypath (index out of bounds)
let keypath = [KeyPath::Index(3)];
let deleted = raw_jsonb.delete_by_keypath(keypath.iter()).unwrap();
assert_eq!(deleted.to_string(), r#"{"a":{"b":[1,2,3]},"c":4}"#); // Original value returned
// Invalid keypath (wrong type)
let keypath = [
KeyPath::Name(Cow::Borrowed("a")),
KeyPath::Name(Cow::Borrowed("x")),
]; // "x" doesn't exist under "a"
let deleted = raw_jsonb.delete_by_keypath(keypath.iter()).unwrap();
assert_eq!(deleted.to_string(), r#"{"a":{"b":[1,2,3]},"c":4}"#); // Original value returned
// Attempting to delete from a scalar
let scalar_jsonb = "1".parse::<OwnedJsonb>().unwrap();
let raw_jsonb = scalar_jsonb.as_raw();
let result = raw_jsonb.delete_by_keypath([].iter());
assert!(result.is_err()); // Returns an error
Sourcepub fn exists_all_keys<'a, I: Iterator<Item = &'a str>>(
&self,
keys: I,
) -> Result<bool, Error>
pub fn exists_all_keys<'a, I: Iterator<Item = &'a str>>( &self, keys: I, ) -> Result<bool, Error>
Checks if all specified keys exist in a JSONB.
This function checks if a JSONB value contains all of the keys provided in the keys
iterator.
If JSONB is an object, check the keys of the object, if it is an array, check the value of type string in the array,
and if it is a scalar, check the value of type string.
§Arguments
self
- The JSONB value.keys
- An iterator of keys to check for.
§Returns
Ok(true)
- If all keys exist in the JSONB.Ok(false)
- If any of the keys do not exist.Err(Error)
- If the input JSONB data is invalid.
§Examples
use jsonb::OwnedJsonb;
let obj_jsonb = r#"{"a": 1, "b": 2, "c": 3}"#.parse::<OwnedJsonb>().unwrap();
let raw_jsonb = obj_jsonb.as_raw();
let keys = ["a", "b", "c"];
assert!(raw_jsonb.exists_all_keys(keys.into_iter()).unwrap());
let keys = ["a", "b", "d"];
assert!(!raw_jsonb.exists_all_keys(keys.into_iter()).unwrap()); // "d" does not exist
let arr_jsonb = r#"["a","b","c"]"#.parse::<OwnedJsonb>().unwrap();
let raw_jsonb = arr_jsonb.as_raw();
let keys = ["a", "b"];
assert!(raw_jsonb.exists_all_keys(keys.into_iter()).unwrap());
let str_jsonb = r#""a""#.parse::<OwnedJsonb>().unwrap();
let raw_jsonb = str_jsonb.as_raw();
let keys = ["b"];
assert!(!raw_jsonb.exists_all_keys(keys.into_iter()).unwrap());
Sourcepub fn exists_any_keys<'a, I: Iterator<Item = &'a str>>(
&self,
keys: I,
) -> Result<bool, Error>
pub fn exists_any_keys<'a, I: Iterator<Item = &'a str>>( &self, keys: I, ) -> Result<bool, Error>
Checks if any of the specified keys exist in a JSONB.
This function checks if a JSONB value contains any of the keys provided in the keys
iterator.
If JSONB is an object, check the keys of the object, if it is an array, check the value of type string in the array,
and if it is a scalar, check the value of type string.
§Arguments
self
- The JSONB value.keys
- An iterator of keys to check for.
§Returns
Ok(true)
- If any of the keys exist in the JSONB.Ok(false)
- If none of the keys exist.Err(Error)
- If the input JSONB data is invalid.
§Examples
use jsonb::OwnedJsonb;
let obj_jsonb = r#"{"a": 1, "b": 2, "c": 3}"#.parse::<OwnedJsonb>().unwrap();
let raw_jsonb = obj_jsonb.as_raw();
let keys = ["a", "d", "e"];
assert!(raw_jsonb.exists_any_keys(keys.into_iter()).unwrap()); // "a" exists
let keys = ["d", "e", "f"];
assert!(!raw_jsonb.exists_any_keys(keys.into_iter()).unwrap()); // None of the keys exist
let arr_jsonb = r#"["a","b","c"]"#.parse::<OwnedJsonb>().unwrap();
let raw_jsonb = arr_jsonb.as_raw();
let keys = ["a", "b"];
assert!(raw_jsonb.exists_any_keys(keys.into_iter()).unwrap());
let str_jsonb = r#""a""#.parse::<OwnedJsonb>().unwrap();
let raw_jsonb = str_jsonb.as_raw();
let keys = ["b"];
assert!(!raw_jsonb.exists_any_keys(keys.into_iter()).unwrap());
Source§impl RawJsonb<'_>
impl RawJsonb<'_>
Sourcepub fn is_null(&self) -> Result<bool, Error>
pub fn is_null(&self) -> Result<bool, Error>
Checks if the JSONB value is null.
This function determines whether the JSONB value represents a JSON null
.
§Arguments
self
- The JSONB value.
§Returns
Ok(true)
if the value is null.Ok(false)
if the value is not null.Err(Error)
- If the input JSONB data is invalid.
§Examples
use jsonb::OwnedJsonb;
let null_jsonb = "null".parse::<OwnedJsonb>().unwrap();
let raw_jsonb = null_jsonb.as_raw();
assert!(raw_jsonb.is_null().unwrap());
let obj_jsonb = r#"{"a": 1}"#.parse::<OwnedJsonb>().unwrap();
let raw_jsonb = obj_jsonb.as_raw();
assert!(!raw_jsonb.is_null().unwrap());
Sourcepub fn as_null(&self) -> Result<Option<()>, Error>
pub fn as_null(&self) -> Result<Option<()>, Error>
Extracts a null value from a JSONB value.
This function returns Some(())
if the value is null and None
otherwise.
Note that this function only checks for the specific JSON null
type; it doesn’t check for empty objects or arrays.
§Arguments
self
- The JSONB value.
§Returns
Ok(Some(()))
- If the value is JSONnull
.Ok(None)
- If the value is not JSONnull
.Err(Error)
- If the JSONB data is invalid.
§Examples
use jsonb::OwnedJsonb;
// JSON null
let null_jsonb = "null".parse::<OwnedJsonb>().unwrap();
let raw_jsonb = null_jsonb.as_raw();
assert!(raw_jsonb.as_null().unwrap().is_some());
// Non-null values
let num_jsonb = "1".parse::<OwnedJsonb>().unwrap();
let raw_jsonb = num_jsonb.as_raw();
assert!(raw_jsonb.as_null().unwrap().is_none());
let arr_jsonb = "[1, 2, 3]".parse::<OwnedJsonb>().unwrap();
let raw_jsonb = arr_jsonb.as_raw();
assert!(raw_jsonb.as_null().unwrap().is_none());
let obj_jsonb = r#"{"a": 1}"#.parse::<OwnedJsonb>().unwrap();
let raw_jsonb = obj_jsonb.as_raw();
assert!(raw_jsonb.as_null().unwrap().is_none());
let empty_array_jsonb = "[]".parse::<OwnedJsonb>().unwrap();
let raw_jsonb = empty_array_jsonb.as_raw();
assert!(raw_jsonb.as_null().unwrap().is_none());
let empty_object_jsonb = "{}".parse::<OwnedJsonb>().unwrap();
let raw_jsonb = empty_object_jsonb.as_raw();
assert!(raw_jsonb.as_null().unwrap().is_none());
// Invalid JSONB
let invalid_jsonb = OwnedJsonb::new(vec![1, 2, 3, 4]);
let invalid_raw_jsonb = invalid_jsonb.as_raw();
let result = invalid_raw_jsonb.as_null();
assert!(result.is_err());
Sourcepub fn is_boolean(&self) -> Result<bool, Error>
pub fn is_boolean(&self) -> Result<bool, Error>
Checks if the JSONB value is a boolean.
This function checks if the JSONB value represents a JSON boolean (true
or false
).
§Arguments
self
- The JSONB value.
§Returns
Ok(true)
- If the value is a boolean (true
orfalse
).Ok(false)
- If the value is not a boolean.Err(Error)
- If the JSONB data is invalid.
§Examples
use jsonb::OwnedJsonb;
// Boolean values
let true_jsonb = "true".parse::<OwnedJsonb>().unwrap();
let raw_true = true_jsonb.as_raw();
assert!(raw_true.is_boolean().unwrap());
let false_jsonb = "false".parse::<OwnedJsonb>().unwrap();
let raw_false = false_jsonb.as_raw();
assert!(raw_false.is_boolean().unwrap());
// Non-boolean values
let num_jsonb = "1".parse::<OwnedJsonb>().unwrap();
let raw_num = num_jsonb.as_raw();
assert!(!raw_num.is_boolean().unwrap());
let arr_jsonb = "[1, 2, 3]".parse::<OwnedJsonb>().unwrap();
let raw_arr = arr_jsonb.as_raw();
assert!(!raw_arr.is_boolean().unwrap());
let obj_jsonb = r#"{"a": 1}"#.parse::<OwnedJsonb>().unwrap();
let raw_obj = obj_jsonb.as_raw();
assert!(!raw_obj.is_boolean().unwrap());
let null_jsonb = "null".parse::<OwnedJsonb>().unwrap();
let raw_null = null_jsonb.as_raw();
assert!(!raw_null.is_boolean().unwrap());
// Invalid JSONB
let invalid_jsonb = OwnedJsonb::new(vec![1, 2, 3, 4]);
let invalid_raw_jsonb = invalid_jsonb.as_raw();
let result = invalid_raw_jsonb.is_boolean();
assert!(result.is_err());
Sourcepub fn as_bool(&self) -> Result<Option<bool>, Error>
pub fn as_bool(&self) -> Result<Option<bool>, Error>
Extracts a boolean value from a JSONB value.
This function attempts to extract a boolean value (true
or false
) from the JSONB value.
If the JSONB value is a boolean, the corresponding boolean value is returned, and return None
otherwise.
§Arguments
self
- The JSONB value.
§Returns
Ok(Some(true))
- If the value is JSONtrue
.Ok(Some(false))
- If the value is JSONfalse
.Ok(None)
- If the value is not a boolean.Err(Error)
- If the JSONB data is invalid.
§Examples
use jsonb::OwnedJsonb;
// Boolean values
let true_jsonb = "true".parse::<OwnedJsonb>().unwrap();
let raw_true = true_jsonb.as_raw();
assert_eq!(raw_true.as_bool().unwrap(), Some(true));
let false_jsonb = "false".parse::<OwnedJsonb>().unwrap();
let raw_false = false_jsonb.as_raw();
assert_eq!(raw_false.as_bool().unwrap(), Some(false));
// Non-boolean values
let num_jsonb = "1".parse::<OwnedJsonb>().unwrap();
let raw_num = num_jsonb.as_raw();
assert_eq!(raw_num.as_bool().unwrap(), None);
let arr_jsonb = "[1, 2, 3]".parse::<OwnedJsonb>().unwrap();
let raw_arr = arr_jsonb.as_raw();
assert_eq!(raw_arr.as_bool().unwrap(), None);
let obj_jsonb = r#"{"a": 1}"#.parse::<OwnedJsonb>().unwrap();
let raw_obj = obj_jsonb.as_raw();
assert_eq!(raw_obj.as_bool().unwrap(), None);
let null_jsonb = "null".parse::<OwnedJsonb>().unwrap();
let raw_null = null_jsonb.as_raw();
assert_eq!(raw_null.as_bool().unwrap(), None);
// Invalid JSONB
let invalid_jsonb = OwnedJsonb::new(vec![1, 2, 3, 4]);
let invalid_raw_jsonb = invalid_jsonb.as_raw();
let result = invalid_raw_jsonb.as_bool();
assert!(result.is_err());
Sourcepub fn to_bool(&self) -> Result<bool, Error>
pub fn to_bool(&self) -> Result<bool, Error>
Converts a JSONB value to a boolean.
This function attempts to convert a JSONB value to a boolean. It prioritizes extracting a boolean value directly if possible. If the value is a string, it converts the string to lowercase and checks if it’s “true” or “false”. Otherwise, it returns an error.
§Arguments
self
- The JSONB value.
§Returns
Ok(true)
- If the value is JSONtrue
or a string that is “true” (case-insensitive).Ok(false)
- If the value is JSONfalse
or a string that is “false” (case-insensitive).Err(Error::InvalidCast)
- If the value cannot be converted to a boolean.Err(Error)
- If the JSONB data is invalid.
§Examples
use jsonb::OwnedJsonb;
// Boolean values
let true_jsonb = "true".parse::<OwnedJsonb>().unwrap();
assert!(true_jsonb.as_raw().to_bool().unwrap());
let false_jsonb = "false".parse::<OwnedJsonb>().unwrap();
assert!(!false_jsonb.as_raw().to_bool().unwrap());
// String representations of booleans
let true_str = r#""true""#.parse::<OwnedJsonb>().unwrap();
assert!(true_str.as_raw().to_bool().unwrap());
let false_str = r#""false""#.parse::<OwnedJsonb>().unwrap();
assert!(!false_str.as_raw().to_bool().unwrap());
let true_str_lowercase = r#""TRUE""#.parse::<OwnedJsonb>().unwrap();
assert!(true_str_lowercase.as_raw().to_bool().unwrap());
// Invalid conversions
let num_jsonb = "1".parse::<OwnedJsonb>().unwrap();
let result = num_jsonb.as_raw().to_bool();
assert!(result.is_err());
let arr_jsonb = "[1, 2, 3]".parse::<OwnedJsonb>().unwrap();
let result = arr_jsonb.as_raw().to_bool();
assert!(result.is_err());
let obj_jsonb = r#"{"a": 1}"#.parse::<OwnedJsonb>().unwrap();
let result = obj_jsonb.as_raw().to_bool();
assert!(result.is_err());
let null_jsonb = "null".parse::<OwnedJsonb>().unwrap();
let result = null_jsonb.as_raw().to_bool();
assert!(result.is_err());
let invalid_str = r#""maybe""#.parse::<OwnedJsonb>().unwrap();
let result = invalid_str.as_raw().to_bool();
assert!(result.is_err());
// Invalid JSONB
let invalid_jsonb = OwnedJsonb::new(vec![1, 2, 3, 4]);
let invalid_raw_jsonb = invalid_jsonb.as_raw();
let result = invalid_raw_jsonb.to_bool();
assert!(result.is_err());
Sourcepub fn is_number(&self) -> Result<bool, Error>
pub fn is_number(&self) -> Result<bool, Error>
Checks if the JSONB value is a number.
This function checks if the JSONB value represents a JSON number.
§Arguments
self
- The JSONB value.
§Returns
Ok(true)
- If the value is a number.Ok(false)
- If the value is not a number.Err(Error)
- If the JSONB data is invalid.
§Examples
use jsonb::OwnedJsonb;
// Number values
let num_jsonb = "123.45".parse::<OwnedJsonb>().unwrap();
let raw_num = num_jsonb.as_raw();
assert!(raw_num.is_number().unwrap());
let num_jsonb = "123".parse::<OwnedJsonb>().unwrap();
let raw_num = num_jsonb.as_raw();
assert!(raw_num.is_number().unwrap());
let num_jsonb = "-123.45".parse::<OwnedJsonb>().unwrap();
let raw_num = num_jsonb.as_raw();
assert!(raw_num.is_number().unwrap());
// Non-number values
let bool_jsonb = "true".parse::<OwnedJsonb>().unwrap();
let raw_bool = bool_jsonb.as_raw();
assert!(!raw_bool.is_number().unwrap());
let str_jsonb = r#""hello""#.parse::<OwnedJsonb>().unwrap();
let raw_str = str_jsonb.as_raw();
assert!(!raw_str.is_number().unwrap());
let arr_jsonb = "[1, 2, 3]".parse::<OwnedJsonb>().unwrap();
let raw_arr = arr_jsonb.as_raw();
assert!(!raw_arr.is_number().unwrap());
let obj_jsonb = r#"{"a": 1}"#.parse::<OwnedJsonb>().unwrap();
let raw_obj = obj_jsonb.as_raw();
assert!(!raw_obj.is_number().unwrap());
let null_jsonb = "null".parse::<OwnedJsonb>().unwrap();
let raw_null = null_jsonb.as_raw();
assert!(!raw_null.is_number().unwrap());
// Invalid JSONB
let invalid_jsonb = OwnedJsonb::new(vec![1, 2, 3, 4]);
let invalid_raw_jsonb = invalid_jsonb.as_raw();
let result = invalid_raw_jsonb.is_number();
assert!(result.is_err());
Sourcepub fn as_number(&self) -> Result<Option<Number>, Error>
pub fn as_number(&self) -> Result<Option<Number>, Error>
Extracts a number from a JSONB value.
This function attempts to extract a number from the JSONB value.
If the JSONB value is a number, it returns the number; otherwise, it returns None
.
§Arguments
self
- The JSONB value.
§Returns
Ok(Some(Number))
- If the value is a number, the extracted number.Ok(None)
- If the value is not a number.Err(Error)
- If the JSONB data is invalid or if the number cannot be decoded.
§Examples
use jsonb::Number;
use jsonb::OwnedJsonb;
use jsonb::RawJsonb;
// Number value
let num_jsonb = "123.45".parse::<OwnedJsonb>().unwrap();
let raw_num = num_jsonb.as_raw();
assert_eq!(raw_num.as_number().unwrap(), Some(Number::Float64(123.45)));
let num_jsonb = "-123".parse::<OwnedJsonb>().unwrap();
let raw_num = num_jsonb.as_raw();
assert_eq!(raw_num.as_number().unwrap(), Some(Number::Int64(-123)));
// Non-number values
let bool_jsonb = "true".parse::<OwnedJsonb>().unwrap();
let raw_bool = bool_jsonb.as_raw();
assert_eq!(raw_bool.as_number().unwrap(), None);
let str_jsonb = r#""hello""#.parse::<OwnedJsonb>().unwrap();
let raw_str = str_jsonb.as_raw();
assert_eq!(raw_str.as_number().unwrap(), None);
let arr_jsonb = "[1, 2, 3]".parse::<OwnedJsonb>().unwrap();
let raw_arr = arr_jsonb.as_raw();
assert_eq!(raw_arr.as_number().unwrap(), None);
let obj_jsonb = r#"{"a": 1}"#.parse::<OwnedJsonb>().unwrap();
let raw_obj = obj_jsonb.as_raw();
assert_eq!(raw_obj.as_number().unwrap(), None);
let null_jsonb = "null".parse::<OwnedJsonb>().unwrap();
let raw_null = null_jsonb.as_raw();
assert_eq!(raw_null.as_number().unwrap(), None);
// Invalid JSONB
let invalid_jsonb = OwnedJsonb::new(vec![1, 2, 3, 4]);
let invalid_raw_jsonb = invalid_jsonb.as_raw();
let result = invalid_raw_jsonb.as_number();
assert!(result.is_err());
// Invalid Number (corrupted data)
let corrupted_num_jsonb = OwnedJsonb::new(vec![10, 0, 0, 0, 16, 0, 0, 0, 0, 1]);
let corrupted_raw_num_jsonb = corrupted_num_jsonb.as_raw();
let result = corrupted_raw_num_jsonb.as_number();
assert!(result.is_err()); // Decodes should return Err
Sourcepub fn is_i64(&self) -> Result<bool, Error>
pub fn is_i64(&self) -> Result<bool, Error>
Checks if the JSONB value is an integer that can be represented as an i64.
This function checks if the JSONB value is a number and can be converted to an i64
without loss of information.
§Arguments
self
- The JSONB value.
§Returns
Ok(true)
- If the value is an integer representable as ani64
.Ok(false)
- If the value is not an integer or cannot be represented as ani64
.Err(Error)
- If the JSONB data is invalid.
§Examples
use jsonb::OwnedJsonb;
// i64 values
let i64_jsonb = "123456789012345678".parse::<OwnedJsonb>().unwrap();
let raw_i64 = i64_jsonb.as_raw();
assert!(raw_i64.is_i64().unwrap());
let i64_jsonb = "-123456789012345678".parse::<OwnedJsonb>().unwrap();
let raw_i64 = i64_jsonb.as_raw();
assert!(raw_i64.is_i64().unwrap());
// Non-i64 values
let float_jsonb = "123.45".parse::<OwnedJsonb>().unwrap();
let raw_float = float_jsonb.as_raw();
assert!(!raw_float.is_i64().unwrap());
let str_jsonb = r#""hello""#.parse::<OwnedJsonb>().unwrap();
let raw_str = str_jsonb.as_raw();
assert!(!raw_str.is_i64().unwrap());
// Invalid JSONB
let invalid_jsonb = OwnedJsonb::new(vec![1, 2, 3, 4]);
let invalid_raw_jsonb = invalid_jsonb.as_raw();
let result = invalid_raw_jsonb.is_i64();
assert!(result.is_err());
Sourcepub fn as_i64(&self) -> Result<Option<i64>, Error>
pub fn as_i64(&self) -> Result<Option<i64>, Error>
Extracts an i64 integer from a JSONB value.
This function attempts to extract an i64
integer from the JSONB value.
If the JSONB value is a number and can be represented as an i64
without loss of information, the integer value is returned.
Otherwise, None
is returned.
§Arguments
self
- The JSONB value.
§Returns
Ok(Some(i64))
- If the value is an integer that can be represented as ani64
.Ok(None)
- If the value is not an integer or cannot be represented as ani64
.Err(Error)
- If the JSONB data is invalid.
§Examples
use jsonb::OwnedJsonb;
// i64 value
let i64_jsonb = "123456789012345678".parse::<OwnedJsonb>().unwrap();
let raw_i64 = i64_jsonb.as_raw();
assert_eq!(raw_i64.as_i64().unwrap(), Some(123456789012345678));
// Non-i64 values
let float_jsonb = "123.45".parse::<OwnedJsonb>().unwrap();
let raw_float = float_jsonb.as_raw();
assert_eq!(raw_float.as_i64().unwrap(), None);
let str_jsonb = r#""hello""#.parse::<OwnedJsonb>().unwrap();
let raw_str = str_jsonb.as_raw();
assert_eq!(raw_str.as_i64().unwrap(), None);
let arr_jsonb = "[1, 2, 3]".parse::<OwnedJsonb>().unwrap();
let raw_arr = arr_jsonb.as_raw();
assert_eq!(raw_arr.as_i64().unwrap(), None);
let obj_jsonb = r#"{"a": 1}"#.parse::<OwnedJsonb>().unwrap();
let raw_obj = obj_jsonb.as_raw();
assert_eq!(raw_obj.as_i64().unwrap(), None);
// Invalid JSONB
let invalid_jsonb = OwnedJsonb::new(vec![1, 2, 3, 4]);
let invalid_raw_jsonb = invalid_jsonb.as_raw();
let result = invalid_raw_jsonb.as_i64();
assert!(result.is_err());
Sourcepub fn to_i64(&self) -> Result<i64, Error>
pub fn to_i64(&self) -> Result<i64, Error>
Converts a JSONB value to an i64 integer.
This function attempts to convert a JSONB value to an i64
integer.
It prioritizes direct conversion from a number if possible.
If the value is a boolean, it’s converted to 1 (for true
) or 0 (for false
).
If the value is a string that can be parsed as an i64
, that parsed value is returned.
Otherwise, an error is returned.
§Arguments
self
- The JSONB value.
§Returns
Ok(i64)
- Thei64
representation of the JSONB value.Err(Error::InvalidCast)
- If the value cannot be converted to ani64
.Err(Error)
- If the JSONB data is invalid.
§Examples
use jsonb::OwnedJsonb;
// Integer values
let i64_jsonb = "123".parse::<OwnedJsonb>().unwrap();
assert_eq!(i64_jsonb.as_raw().to_i64().unwrap(), 123);
let i64_jsonb = "-42".parse::<OwnedJsonb>().unwrap();
assert_eq!(i64_jsonb.as_raw().to_i64().unwrap(), -42);
// Boolean values
let true_jsonb = "true".parse::<OwnedJsonb>().unwrap();
assert_eq!(true_jsonb.as_raw().to_i64().unwrap(), 1);
let false_jsonb = "false".parse::<OwnedJsonb>().unwrap();
assert_eq!(false_jsonb.as_raw().to_i64().unwrap(), 0);
// String representation of an integer
let str_jsonb = r#""123""#.parse::<OwnedJsonb>().unwrap();
assert_eq!(str_jsonb.as_raw().to_i64().unwrap(), 123);
// Invalid conversions
let float_jsonb = "123.45".parse::<OwnedJsonb>().unwrap();
let result = float_jsonb.as_raw().to_i64();
assert!(result.is_err());
let arr_jsonb = "[1, 2, 3]".parse::<OwnedJsonb>().unwrap();
let result = arr_jsonb.as_raw().to_i64();
assert!(result.is_err());
let obj_jsonb = r#"{"a": 1}"#.parse::<OwnedJsonb>().unwrap();
let result = obj_jsonb.as_raw().to_i64();
assert!(result.is_err());
let null_jsonb = "null".parse::<OwnedJsonb>().unwrap();
let result = null_jsonb.as_raw().to_i64();
assert!(result.is_err());
let invalid_str_jsonb = r#""abc""#.parse::<OwnedJsonb>().unwrap();
let result = invalid_str_jsonb.as_raw().to_i64();
assert!(result.is_err());
// Invalid JSONB
let invalid_jsonb = OwnedJsonb::new(vec![1, 2, 3, 4]);
let invalid_raw_jsonb = invalid_jsonb.as_raw();
let result = invalid_raw_jsonb.to_i64();
assert!(result.is_err());
Sourcepub fn is_u64(&self) -> Result<bool, Error>
pub fn is_u64(&self) -> Result<bool, Error>
Checks if the JSONB value is an unsigned integer that can be represented as a u64.
This function checks if the JSONB value is a number and can be converted to a u64
without loss of information.
§Arguments
self
- The JSONB value.
§Returns
Ok(true)
- If the value is an unsigned integer representable as au64
.Ok(false)
- If the value is not an unsigned integer or cannot be represented as au64
.Err(Error)
- If the JSONB data is invalid.
§Examples
use jsonb::OwnedJsonb;
// u64 values
let u64_jsonb = "1234567890123456789".parse::<OwnedJsonb>().unwrap();
let raw_u64 = u64_jsonb.as_raw();
assert!(raw_u64.is_u64().unwrap());
let u64_jsonb = "0".parse::<OwnedJsonb>().unwrap();
let raw_u64 = u64_jsonb.as_raw();
assert!(raw_u64.is_u64().unwrap());
// Non-u64 values
let float_jsonb = "123.45".parse::<OwnedJsonb>().unwrap();
let raw_float = float_jsonb.as_raw();
assert!(!raw_float.is_u64().unwrap());
let negative_num_jsonb = "-123".parse::<OwnedJsonb>().unwrap();
let raw_neg = negative_num_jsonb.as_raw();
assert!(!raw_neg.is_u64().unwrap()); // Negative numbers are not u64
let bool_jsonb = "true".parse::<OwnedJsonb>().unwrap();
let raw_bool = bool_jsonb.as_raw();
assert!(!raw_bool.is_u64().unwrap());
let str_jsonb = r#""hello""#.parse::<OwnedJsonb>().unwrap();
let raw_str = str_jsonb.as_raw();
assert!(!raw_str.is_u64().unwrap());
let arr_jsonb = "[1, 2, 3]".parse::<OwnedJsonb>().unwrap();
let raw_arr = arr_jsonb.as_raw();
assert!(!raw_arr.is_u64().unwrap());
let obj_jsonb = r#"{"a": 1}"#.parse::<OwnedJsonb>().unwrap();
let raw_obj = obj_jsonb.as_raw();
assert!(!raw_obj.is_u64().unwrap());
let null_jsonb = "null".parse::<OwnedJsonb>().unwrap();
let raw_null = null_jsonb.as_raw();
assert!(!raw_null.is_u64().unwrap());
// Invalid JSONB
let invalid_jsonb = OwnedJsonb::new(vec![1, 2, 3, 4]);
let invalid_raw_jsonb = invalid_jsonb.as_raw();
let result = invalid_raw_jsonb.is_u64();
assert!(result.is_err());
Sourcepub fn as_u64(&self) -> Result<Option<u64>, Error>
pub fn as_u64(&self) -> Result<Option<u64>, Error>
Extracts a u64 unsigned integer from a JSONB value.
This function attempts to extract a u64
unsigned integer from the JSONB value.
If the JSONB value is a number and can be represented as a u64
without loss of information (i.e., it’s a non-negative integer within the u64
range),
the unsigned integer value is returned. Otherwise, None
is returned.
§Arguments
self
- The JSONB value.
§Returns
Ok(Some(u64))
- If the value is an unsigned integer that can be represented as au64
.Ok(None)
- If the value is not an unsigned integer or cannot be represented as au64
.Err(Error)
- If the JSONB data is invalid.
§Examples
use jsonb::OwnedJsonb;
// u64 value
let u64_jsonb = "1234567890123456789".parse::<OwnedJsonb>().unwrap();
let raw_u64 = u64_jsonb.as_raw();
assert_eq!(raw_u64.as_u64().unwrap(), Some(1234567890123456789));
// Non-u64 values
let float_jsonb = "123.45".parse::<OwnedJsonb>().unwrap();
let raw_float = float_jsonb.as_raw();
assert_eq!(raw_float.as_u64().unwrap(), None);
let negative_num_jsonb = "-123".parse::<OwnedJsonb>().unwrap();
let raw_neg = negative_num_jsonb.as_raw();
assert_eq!(raw_neg.as_u64().unwrap(), None); // Negative numbers are not u64
let bool_jsonb = "true".parse::<OwnedJsonb>().unwrap();
let raw_bool = bool_jsonb.as_raw();
assert_eq!(raw_bool.as_u64().unwrap(), None);
let str_jsonb = r#""hello""#.parse::<OwnedJsonb>().unwrap();
let raw_str = str_jsonb.as_raw();
assert_eq!(raw_str.as_u64().unwrap(), None);
let arr_jsonb = "[1, 2, 3]".parse::<OwnedJsonb>().unwrap();
let raw_arr = arr_jsonb.as_raw();
assert_eq!(raw_arr.as_u64().unwrap(), None);
let obj_jsonb = r#"{"a": 1}"#.parse::<OwnedJsonb>().unwrap();
let raw_obj = obj_jsonb.as_raw();
assert_eq!(raw_obj.as_u64().unwrap(), None);
let null_jsonb = "null".parse::<OwnedJsonb>().unwrap();
let raw_null = null_jsonb.as_raw();
assert_eq!(raw_null.as_u64().unwrap(), None);
// Invalid JSONB
let invalid_jsonb = OwnedJsonb::new(vec![1, 2, 3, 4]);
let invalid_raw_jsonb = invalid_jsonb.as_raw();
let result = invalid_raw_jsonb.as_u64();
assert!(result.is_err());
Sourcepub fn to_u64(&self) -> Result<u64, Error>
pub fn to_u64(&self) -> Result<u64, Error>
Converts a JSONB value to a u64 unsigned integer.
This function attempts to convert a JSONB value to a u64
unsigned integer.
It prioritizes direct conversion from a number if possible.
If the value is a boolean, it’s converted to 1 (for true
) or 0 (for false
).
If the value is a string that can be parsed as a u64
, that parsed value is returned.
Otherwise, an error is returned.
§Arguments
self
- The JSONB value.
§Returns
Ok(u64)
- Theu64
representation of the JSONB value.Err(Error::InvalidCast)
- If the value cannot be converted to au64
(e.g., it’s a floating-point number, a negative number, an array, an object, or a string that is not a valid unsigned integer).Err(Error)
- If the JSONB data is invalid.
§Examples
use jsonb::OwnedJsonb;
// u64 values
let u64_jsonb = "1234567890123456789".parse::<OwnedJsonb>().unwrap();
assert_eq!(u64_jsonb.as_raw().to_u64().unwrap(), 1234567890123456789);
let u64_jsonb = "0".parse::<OwnedJsonb>().unwrap();
assert_eq!(u64_jsonb.as_raw().to_u64().unwrap(), 0);
// Boolean values
let true_jsonb = "true".parse::<OwnedJsonb>().unwrap();
assert_eq!(true_jsonb.as_raw().to_u64().unwrap(), 1);
let false_jsonb = "false".parse::<OwnedJsonb>().unwrap();
assert_eq!(false_jsonb.as_raw().to_u64().unwrap(), 0);
// String representation of an unsigned integer
let str_jsonb = r#""123""#.parse::<OwnedJsonb>().unwrap();
assert_eq!(str_jsonb.as_raw().to_u64().unwrap(), 123);
// Invalid conversions
let float_jsonb = "123.45".parse::<OwnedJsonb>().unwrap();
let result = float_jsonb.as_raw().to_u64();
assert!(result.is_err());
let negative_num_jsonb = "-123".parse::<OwnedJsonb>().unwrap();
let result = negative_num_jsonb.as_raw().to_u64();
assert!(result.is_err()); // Negative numbers are not u64
let arr_jsonb = "[1, 2, 3]".parse::<OwnedJsonb>().unwrap();
let result = arr_jsonb.as_raw().to_u64();
assert!(result.is_err());
let obj_jsonb = r#"{"a": 1}"#.parse::<OwnedJsonb>().unwrap();
let result = obj_jsonb.as_raw().to_u64();
assert!(result.is_err());
let null_jsonb = "null".parse::<OwnedJsonb>().unwrap();
let result = null_jsonb.as_raw().to_u64();
assert!(result.is_err());
let invalid_str_jsonb = r#""abc""#.parse::<OwnedJsonb>().unwrap();
let result = invalid_str_jsonb.as_raw().to_u64();
assert!(result.is_err());
// Invalid JSONB
let invalid_jsonb = OwnedJsonb::new(vec![1, 2, 3, 4]);
let invalid_raw_jsonb = invalid_jsonb.as_raw();
let result = invalid_raw_jsonb.to_u64();
assert!(result.is_err());
Sourcepub fn is_f64(&self) -> Result<bool, Error>
pub fn is_f64(&self) -> Result<bool, Error>
Checks if the JSONB value is a floating-point number that can be represented as an f64.
This function checks if the JSONB value is a number and can be converted to an f64
without loss of information
(this is generally always true for numbers in JSONB).
§Arguments
self
- The JSONB value.
§Returns
Ok(true)
- If the value is a number.Ok(false)
- If the value is not a number.Err(Error)
- If the JSONB data is invalid.
§Examples
use jsonb::OwnedJsonb;
// f64 values
let f64_jsonb = "123.45".parse::<OwnedJsonb>().unwrap();
let raw_f64 = f64_jsonb.as_raw();
assert!(raw_f64.is_f64().unwrap());
let f64_jsonb = "123".parse::<OwnedJsonb>().unwrap();
let raw_f64 = f64_jsonb.as_raw();
assert!(raw_f64.is_f64().unwrap());
let f64_jsonb = "-123.45".parse::<OwnedJsonb>().unwrap();
let raw_f64 = f64_jsonb.as_raw();
assert!(raw_f64.is_f64().unwrap());
// Non-f64 values
let bool_jsonb = "true".parse::<OwnedJsonb>().unwrap();
let raw_bool = bool_jsonb.as_raw();
assert!(!raw_bool.is_f64().unwrap());
let str_jsonb = r#""hello""#.parse::<OwnedJsonb>().unwrap();
let raw_str = str_jsonb.as_raw();
assert!(!raw_str.is_f64().unwrap());
let arr_jsonb = "[1, 2, 3]".parse::<OwnedJsonb>().unwrap();
let raw_arr = arr_jsonb.as_raw();
assert!(!raw_arr.is_f64().unwrap());
let obj_jsonb = r#"{"a": 1}"#.parse::<OwnedJsonb>().unwrap();
let raw_obj = obj_jsonb.as_raw();
assert!(!raw_obj.is_f64().unwrap());
let null_jsonb = "null".parse::<OwnedJsonb>().unwrap();
let raw_null = null_jsonb.as_raw();
assert!(!raw_null.is_f64().unwrap());
// Invalid JSONB
let invalid_jsonb = OwnedJsonb::new(vec![1, 2, 3, 4]);
let invalid_raw_jsonb = invalid_jsonb.as_raw();
let result = invalid_raw_jsonb.is_f64();
assert!(result.is_err());
Sourcepub fn as_f64(&self) -> Result<Option<f64>, Error>
pub fn as_f64(&self) -> Result<Option<f64>, Error>
Extracts an f64 floating-point number from a JSONB value.
This function attempts to extract an f64
floating-point number from the JSONB value.
If the JSONB value is a number, it’s converted to an f64
and returned. Otherwise, None
is returned.
§Arguments
self
- The JSONB value.
§Returns
Ok(Some(f64))
- If the value is a number, the extractedf64
value.Ok(None)
- If the value is not a number.Err(Error)
- If the JSONB data is invalid.
§Examples
use jsonb::OwnedJsonb;
// f64 values
let f64_jsonb = "123.45".parse::<OwnedJsonb>().unwrap();
let raw_f64 = f64_jsonb.as_raw();
assert_eq!(raw_f64.as_f64().unwrap(), Some(123.45));
let int_jsonb = "123".parse::<OwnedJsonb>().unwrap();
let raw_int = int_jsonb.as_raw();
assert_eq!(raw_int.as_f64().unwrap(), Some(123.0));
// Non-f64 values
let bool_jsonb = "true".parse::<OwnedJsonb>().unwrap();
let raw_bool = bool_jsonb.as_raw();
assert_eq!(raw_bool.as_f64().unwrap(), None);
let str_jsonb = r#""hello""#.parse::<OwnedJsonb>().unwrap();
let raw_str = str_jsonb.as_raw();
assert_eq!(raw_str.as_f64().unwrap(), None);
let arr_jsonb = "[1, 2, 3]".parse::<OwnedJsonb>().unwrap();
let raw_arr = arr_jsonb.as_raw();
assert_eq!(raw_arr.as_f64().unwrap(), None);
let obj_jsonb = r#"{"a": 1}"#.parse::<OwnedJsonb>().unwrap();
let raw_obj = obj_jsonb.as_raw();
assert_eq!(raw_obj.as_f64().unwrap(), None);
let null_jsonb = "null".parse::<OwnedJsonb>().unwrap();
let raw_null = null_jsonb.as_raw();
assert_eq!(raw_null.as_f64().unwrap(), None);
// Invalid JSONB
let invalid_jsonb = OwnedJsonb::new(vec![1, 2, 3, 4]);
let invalid_raw_jsonb = invalid_jsonb.as_raw();
let result = invalid_raw_jsonb.as_f64();
assert!(result.is_err());
Sourcepub fn to_f64(&self) -> Result<f64, Error>
pub fn to_f64(&self) -> Result<f64, Error>
Converts a JSONB value to an f64 floating-point number.
This function attempts to convert a JSONB value to an f64
floating-point number.
It prioritizes direct conversion from a number if possible.
If the value is a boolean, it’s converted to 1.0 (for true
) or 0.0 (for false
).
If the value is a string that can be parsed as an f64
, that parsed value is returned.
Otherwise, an error is returned.
§Arguments
self
- The JSONB value.
§Returns
Ok(f64)
- Thef64
representation of the JSONB value.Err(Error::InvalidCast)
- If the value cannot be converted to anf64
(e.g., it’s an array, an object, a string that is not a valid number, or a null value).Err(Error)
- If the JSONB data is invalid.
§Examples
use jsonb::OwnedJsonb;
// f64 values
let f64_jsonb = "123.45".parse::<OwnedJsonb>().unwrap();
assert_eq!(f64_jsonb.as_raw().to_f64().unwrap(), 123.45);
let int_jsonb = "123".parse::<OwnedJsonb>().unwrap();
assert_eq!(int_jsonb.as_raw().to_f64().unwrap(), 123.0);
// Boolean values
let true_jsonb = "true".parse::<OwnedJsonb>().unwrap();
assert_eq!(true_jsonb.as_raw().to_f64().unwrap(), 1.0);
let false_jsonb = "false".parse::<OwnedJsonb>().unwrap();
assert_eq!(false_jsonb.as_raw().to_f64().unwrap(), 0.0);
// String representation of a number
let str_jsonb = r#""123.45""#.parse::<OwnedJsonb>().unwrap();
assert_eq!(str_jsonb.as_raw().to_f64().unwrap(), 123.45);
// Invalid conversions
let arr_jsonb = "[1, 2, 3]".parse::<OwnedJsonb>().unwrap();
let result = arr_jsonb.as_raw().to_f64();
assert!(result.is_err());
let obj_jsonb = r#"{"a": 1}"#.parse::<OwnedJsonb>().unwrap();
let result = obj_jsonb.as_raw().to_f64();
assert!(result.is_err());
let null_jsonb = "null".parse::<OwnedJsonb>().unwrap();
let result = null_jsonb.as_raw().to_f64();
assert!(result.is_err());
let invalid_str_jsonb = r#""abc""#.parse::<OwnedJsonb>().unwrap();
let result = invalid_str_jsonb.as_raw().to_f64();
assert!(result.is_err());
// Invalid JSONB
let invalid_jsonb = OwnedJsonb::new(vec![1, 2, 3, 4]);
let invalid_raw_jsonb = invalid_jsonb.as_raw();
let result = invalid_raw_jsonb.to_f64();
assert!(result.is_err());
Sourcepub fn is_string(&self) -> Result<bool, Error>
pub fn is_string(&self) -> Result<bool, Error>
Checks if the JSONB value is a string.
This function checks if the JSONB value represents a JSON string.
§Arguments
self
- The JSONB value.
§Returns
Ok(true)
- If the value is a string.Ok(false)
- If the value is not a string.Err(Error)
- If the JSONB data is invalid.
§Examples
use jsonb::OwnedJsonb;
// String value
let str_jsonb = r#""hello""#.parse::<OwnedJsonb>().unwrap();
let raw_str = str_jsonb.as_raw();
assert!(raw_str.is_string().unwrap());
// Non-string values
let num_jsonb = "123".parse::<OwnedJsonb>().unwrap();
let raw_num = num_jsonb.as_raw();
assert!(!raw_num.is_string().unwrap());
let bool_jsonb = "true".parse::<OwnedJsonb>().unwrap();
let raw_bool = bool_jsonb.as_raw();
assert!(!raw_bool.is_string().unwrap());
let arr_jsonb = "[1, 2, 3]".parse::<OwnedJsonb>().unwrap();
let raw_arr = arr_jsonb.as_raw();
assert!(!raw_arr.is_string().unwrap());
let obj_jsonb = r#"{"a": 1}"#.parse::<OwnedJsonb>().unwrap();
let raw_obj = obj_jsonb.as_raw();
assert!(!raw_obj.is_string().unwrap());
let null_jsonb = "null".parse::<OwnedJsonb>().unwrap();
let raw_null = null_jsonb.as_raw();
assert!(!raw_null.is_string().unwrap());
// Invalid JSONB
let invalid_jsonb = OwnedJsonb::new(vec![1, 2, 3, 4]);
let invalid_raw_jsonb = invalid_jsonb.as_raw();
let result = invalid_raw_jsonb.is_string();
assert!(result.is_err());
Sourcepub fn as_str(&self) -> Result<Option<Cow<'_, str>>, Error>
pub fn as_str(&self) -> Result<Option<Cow<'_, str>>, Error>
Extracts a string from a JSONB value.
This function attempts to extract a string from the JSONB value.
If the JSONB value is a string, it returns the string as a Cow<'_, str>
.
Otherwise, it returns None
.
§Arguments
self
- The JSONB value.
§Returns
Ok(Some(Cow<'_, str>))
- If the value is a string, the extracted string.Ok(None)
- If the value is not a string (number, boolean, null, array, object).Err(Error)
- If the JSONB data is invalid or if the string is not valid UTF-8.
§Examples
use jsonb::OwnedJsonb;
use std::borrow::Cow;
// String value
let str_jsonb = r#""hello""#.parse::<OwnedJsonb>().unwrap();
let raw_str = str_jsonb.as_raw();
assert_eq!(raw_str.as_str().unwrap(), Some(Cow::Borrowed("hello")));
// Non-string values
let num_jsonb = "123".parse::<OwnedJsonb>().unwrap();
let raw_num = num_jsonb.as_raw();
assert_eq!(raw_num.as_str().unwrap(), None);
let bool_jsonb = "true".parse::<OwnedJsonb>().unwrap();
let raw_bool = bool_jsonb.as_raw();
assert_eq!(raw_bool.as_str().unwrap(), None);
let arr_jsonb = "[1, 2, 3]".parse::<OwnedJsonb>().unwrap();
let raw_arr = arr_jsonb.as_raw();
assert_eq!(raw_arr.as_str().unwrap(), None);
let obj_jsonb = r#"{"a": 1}"#.parse::<OwnedJsonb>().unwrap();
let raw_obj = obj_jsonb.as_raw();
assert_eq!(raw_obj.as_str().unwrap(), None);
let null_jsonb = "null".parse::<OwnedJsonb>().unwrap();
let raw_null = null_jsonb.as_raw();
assert_eq!(raw_null.as_str().unwrap(), None);
// Invalid JSONB
let invalid_jsonb = OwnedJsonb::new(vec![1, 2, 3, 4]);
let invalid_raw_jsonb = invalid_jsonb.as_raw();
let result = invalid_raw_jsonb.as_str();
assert!(result.is_err());
// Invalid UTF-8 (this will panic in the unsafe block of the original code!)
let invalid_utf8_jsonb = OwnedJsonb::new(vec![10, 0, 0, 0, 16, 0, 0, 0, 0, 150, 151]); // Invalid UTF-8 bytes
let invalid_raw_utf8_jsonb = invalid_utf8_jsonb.as_raw();
let result = invalid_raw_utf8_jsonb.as_str();
assert!(result.is_err());
Sourcepub fn to_str(&self) -> Result<String, Error>
pub fn to_str(&self) -> Result<String, Error>
Converts a JSONB value to a String.
This function attempts to convert a JSONB value to a string representation. It prioritizes direct conversion from strings. Booleans are converted to “true” or “false”, and numbers are converted to their string representations. Other types (arrays, objects, null) will result in an error.
§Arguments
self
- The JSONB value.
§Returns
Ok(String)
- The string representation of the JSONB value.Err(Error::InvalidCast)
- If the JSONB value cannot be converted to a string (e.g., it’s an array, an object, or a null value).Err(Error)
- If the JSONB data is invalid.
§Examples
use jsonb::OwnedJsonb;
// String value
let str_jsonb = r#""hello""#.parse::<OwnedJsonb>().unwrap();
assert_eq!(str_jsonb.as_raw().to_str().unwrap(), "hello");
// Number value
let num_jsonb = "123.45".parse::<OwnedJsonb>().unwrap();
assert_eq!(num_jsonb.as_raw().to_str().unwrap(), "123.45");
// Boolean values
let true_jsonb = "true".parse::<OwnedJsonb>().unwrap();
assert_eq!(true_jsonb.as_raw().to_str().unwrap(), "true");
let false_jsonb = "false".parse::<OwnedJsonb>().unwrap();
assert_eq!(false_jsonb.as_raw().to_str().unwrap(), "false");
// Invalid conversions
let arr_jsonb = "[1, 2, 3]".parse::<OwnedJsonb>().unwrap();
let result = arr_jsonb.as_raw().to_str();
assert!(result.is_err());
let obj_jsonb = r#"{"a": 1}"#.parse::<OwnedJsonb>().unwrap();
let result = obj_jsonb.as_raw().to_str();
assert!(result.is_err());
let null_jsonb = "null".parse::<OwnedJsonb>().unwrap();
let result = null_jsonb.as_raw().to_str();
assert!(result.is_err());
// Invalid JSONB
let invalid_jsonb = OwnedJsonb::new(vec![1, 2, 3, 4]);
let invalid_raw_jsonb = invalid_jsonb.as_raw();
let result = invalid_raw_jsonb.to_str();
assert!(result.is_err());
Sourcepub fn is_array(&self) -> Result<bool, Error>
pub fn is_array(&self) -> Result<bool, Error>
Checks if the JSONB value is an array.
This function checks if the JSONB value represents a JSON array.
§Arguments
self
- The JSONB value.
§Returns
Ok(true)
- If the value is an array.Ok(false)
- If the value is not an array.Err(Error)
- If the JSONB data is invalid.
§Examples
use jsonb::OwnedJsonb;
// Array value
let arr_jsonb = "[1, 2, 3]".parse::<OwnedJsonb>().unwrap();
let raw_arr = arr_jsonb.as_raw();
assert!(raw_arr.is_array().unwrap());
// Non-array values
let num_jsonb = "123".parse::<OwnedJsonb>().unwrap();
let raw_num = num_jsonb.as_raw();
assert!(!raw_num.is_array().unwrap());
let bool_jsonb = "true".parse::<OwnedJsonb>().unwrap();
let raw_bool = bool_jsonb.as_raw();
assert!(!raw_bool.is_array().unwrap());
let str_jsonb = r#""hello""#.parse::<OwnedJsonb>().unwrap();
let raw_str = str_jsonb.as_raw();
assert!(!raw_str.is_array().unwrap());
let obj_jsonb = r#"{"a": 1}"#.parse::<OwnedJsonb>().unwrap();
let raw_obj = obj_jsonb.as_raw();
assert!(!raw_obj.is_array().unwrap());
let null_jsonb = "null".parse::<OwnedJsonb>().unwrap();
let raw_null = null_jsonb.as_raw();
assert!(!raw_null.is_array().unwrap());
// Invalid JSONB
let invalid_jsonb = OwnedJsonb::new(vec![1, 2, 3, 4]);
let invalid_raw_jsonb = invalid_jsonb.as_raw();
let result = invalid_raw_jsonb.is_array();
assert!(result.is_err());
Sourcepub fn is_object(&self) -> Result<bool, Error>
pub fn is_object(&self) -> Result<bool, Error>
Checks if the JSONB value is an object.
This function checks if the JSONB value represents a JSON object.
§Arguments
self
- The JSONB value.
§Returns
Ok(true)
- If the value is an object.Ok(false)
- If the value is not an object.Err(Error)
- If the JSONB data is invalid.
§Examples
use jsonb::OwnedJsonb;
// Object value
let obj_jsonb = r#"{"a": 1}"#.parse::<OwnedJsonb>().unwrap();
let raw_obj = obj_jsonb.as_raw();
assert!(raw_obj.is_object().unwrap());
// Non-object values
let num_jsonb = "123".parse::<OwnedJsonb>().unwrap();
let raw_num = num_jsonb.as_raw();
assert!(!raw_num.is_object().unwrap());
let bool_jsonb = "true".parse::<OwnedJsonb>().unwrap();
let raw_bool = bool_jsonb.as_raw();
assert!(!raw_bool.is_object().unwrap());
let str_jsonb = r#""hello""#.parse::<OwnedJsonb>().unwrap();
let raw_str = str_jsonb.as_raw();
assert!(!raw_str.is_object().unwrap());
let arr_jsonb = "[1, 2, 3]".parse::<OwnedJsonb>().unwrap();
let raw_arr = arr_jsonb.as_raw();
assert!(!raw_arr.is_object().unwrap());
let null_jsonb = "null".parse::<OwnedJsonb>().unwrap();
let raw_null = null_jsonb.as_raw();
assert!(!raw_null.is_object().unwrap());
// Invalid JSONB
let invalid_jsonb = OwnedJsonb::new(vec![1, 2, 3, 4]);
let invalid_raw_jsonb = invalid_jsonb.as_raw();
let result = invalid_raw_jsonb.is_object();
assert!(result.is_err());
Sourcepub fn is_extension_value(&self) -> Result<bool, Error>
pub fn is_extension_value(&self) -> Result<bool, Error>
Checks if the JSONB value is a extension(binary, date, timestamp, timestamp_tz, interval) value.
This function checks if the JSONB value represents a extension value.
§Arguments
self
- The JSONB value.
§Returns
Ok(true)
- If the value is a extension value.Ok(false)
- If the value is not a extension value.Err(Error)
- If the JSONB data is invalid.
§Examples
use jsonb::RawJsonb;
use jsonb::Value;
// Binary value
let binary_value = Value::Binary(&[1,2,3]);
let buf = binary_value.to_vec();
let raw_jsonb = RawJsonb::new(&buf);
assert!(raw_jsonb.is_extension_value().unwrap());
Sourcepub fn as_extension_value(&self) -> Result<Option<ExtensionValue<'_>>, Error>
pub fn as_extension_value(&self) -> Result<Option<ExtensionValue<'_>>, Error>
Extracts a extension value from a JSONB value.
This function attempts to extract a extension value from the JSONB value.
§Arguments
self
- The JSONB value.
§Returns
Ok(Some(ExtensionValue))
- If the value is a extension value, the extracted extension value.Ok(None)
- If the value is not a extension value.Err(Error)
- If the JSONB data is invalid or if the extension value cannot be decoded.
§Examples
use jsonb::ExtensionValue;
use jsonb::RawJsonb;
use jsonb::Value;
// Binary value
let binary_value = Value::Binary(&[1,2,3]);
let buf = binary_value.to_vec();
let raw_jsonb = RawJsonb::new(&buf);
assert_eq!(raw_jsonb.as_extension_value().unwrap(), Some(ExtensionValue::Binary(&[1,2,3])));
Sourcepub fn is_binary(&self) -> Result<bool, Error>
pub fn is_binary(&self) -> Result<bool, Error>
Checks if the JSONB value is a binary value.
This function checks if the JSONB value represents a binary value.
§Arguments
self
- The JSONB value.
§Returns
Ok(true)
- If the value is a binary value.Ok(false)
- If the value is not a binary value.Err(Error)
- If the JSONB data is invalid.
§Examples
use jsonb::RawJsonb;
use jsonb::Value;
// Binary value
let binary_value = Value::Binary(&[1,2,3]);
let buf = binary_value.to_vec();
let raw_jsonb = RawJsonb::new(&buf);
assert!(raw_jsonb.is_binary().unwrap());
Sourcepub fn as_binary(&self) -> Result<Option<Vec<u8>>, Error>
pub fn as_binary(&self) -> Result<Option<Vec<u8>>, Error>
Extracts a binary value from a JSONB value.
This function attempts to extract a binary value from the JSONB value.
§Arguments
self
- The JSONB value.
§Returns
Ok(Some(Vec<u8>))
- If the value is a binary value, the extracted binary value.Ok(None)
- If the value is not a binary value.Err(Error)
- If the JSONB data is invalid or if the binary value cannot be decoded.
§Examples
use jsonb::RawJsonb;
use jsonb::Value;
// Binary value
let binary_value = Value::Binary(&[1,2,3]);
let buf = binary_value.to_vec();
let raw_jsonb = RawJsonb::new(&buf);
assert_eq!(raw_jsonb.as_binary().unwrap(), Some(vec![1,2,3]));
Sourcepub fn is_date(&self) -> Result<bool, Error>
pub fn is_date(&self) -> Result<bool, Error>
Checks if the JSONB value is a date value.
This function checks if the JSONB value represents a date value.
§Arguments
self
- The JSONB value.
§Returns
Ok(true)
- If the value is a date value.Ok(false)
- If the value is not a date value.Err(Error)
- If the JSONB data is invalid.
§Examples
use jsonb::Date;
use jsonb::RawJsonb;
use jsonb::Value;
// Date value
let date_value = Value::Date(Date { value: 20372 });
let buf = date_value.to_vec();
let raw_jsonb = RawJsonb::new(&buf);
assert!(raw_jsonb.is_date().unwrap());
Sourcepub fn as_date(&self) -> Result<Option<Date>, Error>
pub fn as_date(&self) -> Result<Option<Date>, Error>
Extracts a date value from a JSONB value.
This function attempts to extract a date value from the JSONB value.
§Arguments
self
- The JSONB value.
§Returns
Ok(Some(Date))
- If the value is a date value, the extracted date value.Ok(None)
- If the value is not a date value.Err(Error)
- If the JSONB data is invalid or if the date value cannot be decoded.
§Examples
use jsonb::Date;
use jsonb::RawJsonb;
use jsonb::Value;
// Date value
let date_value = Value::Date(Date { value: 20372 });
let buf = date_value.to_vec();
let raw_jsonb = RawJsonb::new(&buf);
assert_eq!(raw_jsonb.as_date().unwrap(), Some(Date { value: 20372 }));
Sourcepub fn is_timestamp(&self) -> Result<bool, Error>
pub fn is_timestamp(&self) -> Result<bool, Error>
Checks if the JSONB value is a timestamp value.
This function checks if the JSONB value represents a timestamp value.
§Arguments
self
- The JSONB value.
§Returns
Ok(true)
- If the value is a timestamp value.Ok(false)
- If the value is not a timestamp value.Err(Error)
- If the JSONB data is invalid.
§Examples
use jsonb::Timestamp;
use jsonb::RawJsonb;
use jsonb::Value;
// Timestamp value
let timestamp_value = Value::Timestamp(Timestamp { value: 1760140800000000 });
let buf = timestamp_value.to_vec();
let raw_jsonb = RawJsonb::new(&buf);
assert!(raw_jsonb.is_timestamp().unwrap());
Sourcepub fn as_timestamp(&self) -> Result<Option<Timestamp>, Error>
pub fn as_timestamp(&self) -> Result<Option<Timestamp>, Error>
Extracts a timestamp value from a JSONB value.
This function attempts to extract a timestamp value from the JSONB value.
§Arguments
self
- The JSONB value.
§Returns
Ok(Some(Timestamp))
- If the value is a timestamp value, the extracted timestamp value.Ok(None)
- If the value is not a timestamp value.Err(Error)
- If the JSONB data is invalid or if the timestamp value cannot be decoded.
§Examples
use jsonb::Timestamp;
use jsonb::RawJsonb;
use jsonb::Value;
// Timestamp value
let timestamp_value = Value::Timestamp(Timestamp { value: 1760140800000000 });
let buf = timestamp_value.to_vec();
let raw_jsonb = RawJsonb::new(&buf);
assert_eq!(raw_jsonb.as_timestamp().unwrap(), Some(Timestamp { value: 1760140800000000 }));
Sourcepub fn is_timestamp_tz(&self) -> Result<bool, Error>
pub fn is_timestamp_tz(&self) -> Result<bool, Error>
Checks if the JSONB value is a timestamp tz value.
This function checks if the JSONB value represents a timestamp tz value.
§Arguments
self
- The JSONB value.
§Returns
Ok(true)
- If the value is a timestamp tz value.Ok(false)
- If the value is not a timestamp tz value.Err(Error)
- If the JSONB data is invalid.
§Examples
use jsonb::TimestampTz;
use jsonb::RawJsonb;
use jsonb::Value;
// TimestampTz value
let timestamp_tz_value = Value::TimestampTz(TimestampTz { offset: 8, value: 1760140800000000 });
let buf = timestamp_tz_value.to_vec();
let raw_jsonb = RawJsonb::new(&buf);
assert!(raw_jsonb.is_timestamp_tz().unwrap());
Sourcepub fn as_timestamp_tz(&self) -> Result<Option<TimestampTz>, Error>
pub fn as_timestamp_tz(&self) -> Result<Option<TimestampTz>, Error>
Extracts a timestamp tz value from a JSONB value.
This function attempts to extract a timestamp tz value from the JSONB value.
§Arguments
self
- The JSONB value.
§Returns
Ok(Some(TimestampTz))
- If the value is a timestamp tz value, the extracted timestamp value.Ok(None)
- If the value is not a timestamp tz value.Err(Error)
- If the JSONB data is invalid or if the timestamp tz value cannot be decoded.
§Examples
use jsonb::TimestampTz;
use jsonb::RawJsonb;
use jsonb::Value;
// TimestampTz value
let timestamp_tz_value = Value::TimestampTz(TimestampTz { offset: 8, value: 1760140800000000 });
let buf = timestamp_tz_value.to_vec();
let raw_jsonb = RawJsonb::new(&buf);
assert_eq!(raw_jsonb.as_timestamp_tz().unwrap(), Some(TimestampTz { offset: 8, value: 1760140800000000 }));
Sourcepub fn is_interval(&self) -> Result<bool, Error>
pub fn is_interval(&self) -> Result<bool, Error>
Checks if the JSONB value is a interval value.
This function checks if the JSONB value represents a interval value.
§Arguments
self
- The JSONB value.
§Returns
Ok(true)
- If the value is a interval value.Ok(false)
- If the value is not a interval value.Err(Error)
- If the JSONB data is invalid.
§Examples
use jsonb::Interval;
use jsonb::RawJsonb;
use jsonb::Value;
// Interval value
let interval_value = Value::Interval(Interval { months: 10, days: 20, micros: 300000000 });
let buf = interval_value.to_vec();
let raw_jsonb = RawJsonb::new(&buf);
assert!(raw_jsonb.is_interval().unwrap());
Sourcepub fn as_interval(&self) -> Result<Option<Interval>, Error>
pub fn as_interval(&self) -> Result<Option<Interval>, Error>
Extracts a interval value from a JSONB value.
This function attempts to extract a interval value from the JSONB value.
§Arguments
self
- The JSONB value.
§Returns
Ok(Some(Interval))
- If the value is a interval value, the extracted timestamp value.Ok(None)
- If the value is not a interval value.Err(Error)
- If the JSONB data is invalid or if the interval value cannot be decoded.
§Examples
use jsonb::Interval;
use jsonb::RawJsonb;
use jsonb::Value;
// Interval value
let interval_value = Value::Interval(Interval { months: 10, days: 20, micros: 300000000 });
let buf = interval_value.to_vec();
let raw_jsonb = RawJsonb::new(&buf);
assert_eq!(raw_jsonb.as_interval().unwrap(), Some(Interval { months: 10, days: 20, micros: 300000000 }));
Source§impl<'a> RawJsonb<'a>
impl<'a> RawJsonb<'a>
Sourcepub fn to_owned(&self) -> OwnedJsonb
pub fn to_owned(&self) -> OwnedJsonb
Creates an OwnedJsonb
from the RawJsonb
by copying the underlying data.
This method converts a RawJsonb
, which holds a reference to JSONB data,
into an OwnedJsonb
, which owns its own copy of the JSONB data. This is
achieved by cloning the byte slice held by the RawJsonb
into a new Vec<u8>
.
§Returns
An OwnedJsonb
instance containing a copy of the JSONB data from the RawJsonb
.
Sourcepub fn to_string(&self) -> String
pub fn to_string(&self) -> String
Converts the JSONB value to a JSON string.
This function serializes the JSONB value into a human-readable JSON string representation. If the JSONB data is invalid, treate it as a text JSON string and return directly. If the JSONB data is empty, return a JSON null for compatibility.
§Returns
String
- The JSON string representation of the value.
§Examples
use jsonb::OwnedJsonb;
let arr_jsonb = "[1, 2, 3]".parse::<OwnedJsonb>().unwrap();
let raw_jsonb = arr_jsonb.as_raw();
assert_eq!(raw_jsonb.to_string(), "[1,2,3]");
let obj_jsonb = r#"{"a": 1, "b": "hello"}"#.parse::<OwnedJsonb>().unwrap();
let raw_jsonb = obj_jsonb.as_raw();
assert_eq!(raw_jsonb.to_string(), r#"{"a":1,"b":"hello"}"#);
let num_jsonb = "123.45".parse::<OwnedJsonb>().unwrap();
let raw_jsonb = num_jsonb.as_raw();
assert_eq!(raw_jsonb.to_string(), "123.45");
let string_jsonb = r#""hello, world!""#.parse::<OwnedJsonb>().unwrap();
let raw_jsonb = string_jsonb.as_raw();
assert_eq!(raw_jsonb.to_string(), r#""hello, world!""#);
let true_jsonb = "true".parse::<OwnedJsonb>().unwrap();
let raw_jsonb = true_jsonb.as_raw();
assert_eq!(raw_jsonb.to_string(), "true");
// Example with invalid JSONB data (fallback to treat as text JSON string)
let invalid_jsonb = OwnedJsonb::new(vec![1, 2, 3, 4]); // Invalid binary JSONB
let invalid_raw_jsonb = invalid_jsonb.as_raw();
// It will treat as text JSON string.
assert_eq!(invalid_raw_jsonb.to_string(), "\u{1}\u{2}\u{3}\u{4}");
Sourcepub fn to_pretty_string(&self) -> String
pub fn to_pretty_string(&self) -> String
Converts the JSONB value to a pretty-printed JSON string.
This function serializes the JSONB value into a human-readable JSON string representation with indentation for formatting. If the JSONB data is invalid, return a “null” string.
§Returns
String
- The pretty-printed JSON string representation of the value.
§Examples
use jsonb::OwnedJsonb;
let arr_jsonb = "[1, 2, 3]".parse::<OwnedJsonb>().unwrap();
let raw_jsonb = arr_jsonb.as_raw();
assert_eq!(raw_jsonb.to_pretty_string(), "[\n 1,\n 2,\n 3\n]");
let obj_jsonb = r#"{"a": 1, "b": "hello"}"#.parse::<OwnedJsonb>().unwrap();
let raw_jsonb = obj_jsonb.as_raw();
assert_eq!(
raw_jsonb.to_pretty_string(),
"{\n \"a\": 1,\n \"b\": \"hello\"\n}"
);
let num_jsonb = "123.45".parse::<OwnedJsonb>().unwrap();
let raw_jsonb = num_jsonb.as_raw();
assert_eq!(raw_jsonb.to_pretty_string(), "123.45");
let string_jsonb = r#""hello, world!""#.parse::<OwnedJsonb>().unwrap();
let raw_jsonb = string_jsonb.as_raw();
assert_eq!(raw_jsonb.to_pretty_string(), r#""hello, world!""#);
// Example with invalid JSONB data (fallback to text JSON parsing)
let invalid_jsonb = OwnedJsonb::new(vec![1, 2, 3, 4]); // Invalid binary JSONB
let invalid_raw_jsonb = invalid_jsonb.as_raw();
assert_eq!(invalid_raw_jsonb.to_pretty_string(), "null"); // Fails and returns "null"
Trait Implementations§
Source§impl AsRef<[u8]> for RawJsonb<'_>
Allows accessing the underlying byte slice as a reference.
This enables easy integration with functions that expect a &u8.
impl AsRef<[u8]> for RawJsonb<'_>
Allows accessing the underlying byte slice as a reference. This enables easy integration with functions that expect a &u8.
Source§impl<'a> From<&'a [u8]> for RawJsonb<'a>
Converts a borrowed byte slice into a RawJsonb.
This provides a convenient way to create a RawJsonb from existing data without copying.
impl<'a> From<&'a [u8]> for RawJsonb<'a>
Converts a borrowed byte slice into a RawJsonb. This provides a convenient way to create a RawJsonb from existing data without copying.
Source§impl Ord for RawJsonb<'_>
Implements Ord
for RawJsonb
, allowing comparison of two RawJsonb
values using the total ordering.
This implementation leverages the PartialOrd
implementation, returning Ordering::Equal
for incomparable values.
impl Ord for RawJsonb<'_>
Implements Ord
for RawJsonb
, allowing comparison of two RawJsonb
values using the total ordering.
This implementation leverages the PartialOrd
implementation, returning Ordering::Equal
for incomparable values.
Source§impl PartialOrd for RawJsonb<'_>
Implements PartialOrd
for RawJsonb
, allowing comparison of two RawJsonb
values.
impl PartialOrd for RawJsonb<'_>
Implements PartialOrd
for RawJsonb
, allowing comparison of two RawJsonb
values.
The comparison logic handles different JSONB types (scalar, array, object) and considers null values. The ordering is defined as follows:
- Null is considered greater than any other type.
- Scalars are compared based on their type and value (String > Number > Boolean > ExtensionValue).
- Arrays are compared element by element.
- Objects are compared based on their keys and values.
- Arrays are greater than objects and scalars.
- Objects are greater than scalars.
- If the types are incompatible, None is returned.
impl<'a> Copy for RawJsonb<'a>
impl Eq for RawJsonb<'_>
Auto Trait Implementations§
impl<'a> Freeze for RawJsonb<'a>
impl<'a> RefUnwindSafe for RawJsonb<'a>
impl<'a> Send for RawJsonb<'a>
impl<'a> Sync for RawJsonb<'a>
impl<'a> Unpin for RawJsonb<'a>
impl<'a> UnwindSafe for RawJsonb<'a>
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Source§impl<Q, K> Comparable<K> for Q
impl<Q, K> Comparable<K> for Q
Source§impl<Q, K> Equivalent<K> for Q
impl<Q, K> Equivalent<K> for Q
Source§impl<Q, K> Equivalent<K> for Q
impl<Q, K> Equivalent<K> for Q
Source§fn equivalent(&self, key: &K) -> bool
fn equivalent(&self, key: &K) -> bool
key
and return true
if they are equal.