from_raw_jsonb

Function from_raw_jsonb 

Source
pub fn from_raw_jsonb<'de, T>(raw_jsonb: &'de RawJsonb<'_>) -> Result<T, Error>
where T: Deserialize<'de>,
Expand description

Deserializes a RawJsonb into a Rust data structure using Serde.

This function takes a RawJsonb (a borrowed slice of JSONB data) and attempts to deserialize it into a Rust type T that implements the Deserialize trait. It uses a custom Deserializer to handle the JSONB data.

§Arguments

  • raw_jsonb: A reference to the RawJsonb containing the JSONB data to deserialize.

§Type Parameters

  • T: The Rust type to deserialize the JSONB data into. This type must implement the serde::de::Deserialize trait.

§Returns

  • Ok(t): If the deserialization is successful, returns the deserialized value of type T.
  • Err(Error::InvalidJsonb): If the deserialization fails due to invalid JSONB data (e.g., trailing characters after the expected JSONB structure).
  • Err(e): If any other Serde deserialization error occurs.

§Examples

use jsonb::from_raw_jsonb;
use jsonb::OwnedJsonb;
use jsonb::RawJsonb;
use serde::Deserialize;

#[derive(Deserialize, Debug, PartialEq, Eq)]
struct Person {
    name: String,
    age: u32,
}

let owned_jsonb = r#"{"name": "Alice", "age": 20}"#.parse::<OwnedJsonb>().unwrap();
let raw_jsonb = owned_jsonb.as_raw();

let person: Person = from_raw_jsonb(&raw_jsonb).unwrap();
assert_eq!(person, Person { name: "Alice".to_string(), age: 20 });
println!("{:?}", person); // Output: Person { name: "Alice", age: 20 }