Skip to main content

JsonRawValue

Struct JsonRawValue 

Source
pub struct JsonRawValue { /* private fields */ }
Available on crate features json and raw_value only.
Expand description

Reference to a range of bytes encompassing a single valid JSON value in the input data.

A RawValue can be used to defer parsing parts of a payload until later, or to avoid parsing it at all in the case that part of the payload just needs to be transferred verbatim into a different output object.

When serializing, a value of this type will retain its original formatting and will not be minified or pretty-printed.

ยงNote

RawValue is only available if serde_json is built with the "raw_value" feature.

[dependencies]
serde_json = { version = "1.0", features = ["raw_value"] }

ยงExample

use serde::{Deserialize, Serialize};
use serde_json::{Result, value::RawValue};

#[derive(Deserialize)]
struct Input<'a> {
    code: u32,
    #[serde(borrow)]
    payload: &'a RawValue,
}

#[derive(Serialize)]
struct Output<'a> {
    info: (u32, &'a RawValue),
}

// Efficiently rearrange JSON input containing separate "code" and "payload"
// keys into a single "info" key holding an array of code and payload.
//
// This could be done equivalently using serde_json::Value as the type for
// payload, but &RawValue will perform better because it does not require
// memory allocation. The correct range of bytes is borrowed from the input
// data and pasted verbatim into the output.
fn rearrange(input: &str) -> Result<String> {
    let input: Input = serde_json::from_str(input)?;

    let output = Output {
        info: (input.code, input.payload),
    };

    serde_json::to_string(&output)
}

fn main() -> Result<()> {
    let out = rearrange(r#" {"code": 200, "payload": {}} "#)?;

    assert_eq!(out, r#"{"info":[200,{}]}"#);

    Ok(())
}

ยงOwnership

The typical usage of RawValue will be in the borrowed form:

#[derive(Deserialize)]
struct SomeStruct<'a> {
    #[serde(borrow)]
    raw_value: &'a RawValue,
}

The borrowed form is suitable when deserializing through serde_json::from_str and serde_json::from_slice which support borrowing from the input data without memory allocation.

When deserializing through serde_json::from_reader you will need to use the boxed form of RawValue instead. This is almost as efficient but involves buffering the raw value from the I/O stream into memory.

#[derive(Deserialize)]
struct SomeStruct {
    raw_value: Box<RawValue>,
}

Implementationsยง

Sourceยง

impl RawValue

Source

pub const NULL: &'static RawValue

A constant RawValue with the JSON value null.

Source

pub const TRUE: &'static RawValue

A constant RawValue with the JSON value true.

Source

pub const FALSE: &'static RawValue

A constant RawValue with the JSON value false.

Source

pub fn from_string(json: String) -> Result<Box<RawValue>, Error>

Convert an owned String of JSON data to an owned RawValue.

This function is equivalent to serde_json::from_str::<Box<RawValue>> except that we avoid an allocation and memcpy if both of the following are true:

  • the input has no leading or trailing whitespace, and
  • the input has capacity equal to its length.
Source

pub unsafe fn from_string_unchecked(json: String) -> Box<RawValue>

Convert an owned String of JSON data to an owned RawValue without checking that it contains valid JSON.

This is the unchecked counterpart of RawValue::from_string, for strings that are already known to be valid JSON, such as the output of another JSON serializer. Unlike from_string, it does not re-parse the string; the only cost is String::into_boxed_str.

ยงSafety

The string passed in must contain a single well-formed JSON value with no leading or trailing whitespace. RawValue is written verbatim into JSON output wherever it is embedded, and other code (including unsafe code) is allowed to rely on RawValue upholding this invariant, in the same way that unsafe code may rely on str containing valid UTF-8.

In debug builds this contract is checked with a debug_assert! that re-parses the input; the check is compiled out in release builds, so only release performance matches the โ€œno re-parseโ€ guarantee above.

ยงExample
use serde_json::value::RawValue;

let json = serde_json::to_string(&[1, 2, 3])?;

// SAFETY: `json` was produced by serde_json's own serializer, so it is
// a single well-formed JSON value without surrounding whitespace.
let raw = unsafe { RawValue::from_string_unchecked(json) };

assert_eq!(raw.get(), "[1,2,3]");
Source

pub fn get(&self) -> &str

Access the JSON text underlying a raw value.

ยงExample
use serde::Deserialize;
use serde_json::{Result, value::RawValue};

#[derive(Deserialize)]
struct Response<'a> {
    code: u32,
    #[serde(borrow)]
    payload: &'a RawValue,
}

fn process(input: &str) -> Result<()> {
    let response: Response = serde_json::from_str(input)?;

    let payload = response.payload.get();
    if payload.starts_with('{') {
        // handle a payload which is a JSON map
    } else {
        // handle any other type
    }

    Ok(())
}

fn main() -> Result<()> {
    process(r#" {"code": 200, "payload": {}} "#)?;
    Ok(())
}

Trait Implementationsยง

Sourceยง

impl Clone for Box<RawValue>

Sourceยง

fn clone(&self) -> Box<RawValue>

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) ยท Sourceยง

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Sourceยง

impl Debug for RawValue

Sourceยง

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

Formats the value using the given formatter. Read more
Sourceยง

impl<'r, DB> Decode<'r, DB> for &'r RawValue
where Json<&'r RawValue>: Decode<'r, DB>, DB: Database,

Sourceยง

fn decode( value: <DB as HasValueRef<'r>>::ValueRef, ) -> Result<&'r RawValue, Box<dyn Error + Send + Sync>>

Decode a new value of this type using a raw value from the database.
Sourceยง

impl Default for Box<RawValue>

Sourceยง

fn default() -> Box<RawValue>

Returns the โ€œdefault valueโ€ for a type. Read more
Sourceยง

impl<'de, 'a> Deserialize<'de> for &'a RawValue
where 'de: 'a,

Sourceยง

fn deserialize<D>( deserializer: D, ) -> Result<&'a RawValue, <D as Deserializer<'de>>::Error>
where D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Sourceยง

impl<'de> Deserialize<'de> for Box<RawValue>

Sourceยง

fn deserialize<D>( deserializer: D, ) -> Result<Box<RawValue>, <D as Deserializer<'de>>::Error>
where D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Sourceยง

impl<'de> Deserializer<'de> for &'de RawValue

Sourceยง

type Error = Error

The error type that can be returned if some error occurs during deserialization.
Sourceยง

fn deserialize_any<V>( self, visitor: V, ) -> Result<<V as Visitor<'de>>::Value, Error>
where V: Visitor<'de>,

Require the Deserializer to figure out how to drive the visitor based on what data type is in the input. Read more
Sourceยง

fn deserialize_bool<V>( self, visitor: V, ) -> Result<<V as Visitor<'de>>::Value, Error>
where V: Visitor<'de>,

Hint that the Deserialize type is expecting a bool value.
Sourceยง

fn deserialize_i8<V>( self, visitor: V, ) -> Result<<V as Visitor<'de>>::Value, Error>
where V: Visitor<'de>,

Hint that the Deserialize type is expecting an i8 value.
Sourceยง

fn deserialize_i16<V>( self, visitor: V, ) -> Result<<V as Visitor<'de>>::Value, Error>
where V: Visitor<'de>,

Hint that the Deserialize type is expecting an i16 value.
Sourceยง

fn deserialize_i32<V>( self, visitor: V, ) -> Result<<V as Visitor<'de>>::Value, Error>
where V: Visitor<'de>,

Hint that the Deserialize type is expecting an i32 value.
Sourceยง

fn deserialize_i64<V>( self, visitor: V, ) -> Result<<V as Visitor<'de>>::Value, Error>
where V: Visitor<'de>,

Hint that the Deserialize type is expecting an i64 value.
Sourceยง

fn deserialize_i128<V>( self, visitor: V, ) -> Result<<V as Visitor<'de>>::Value, Error>
where V: Visitor<'de>,

Hint that the Deserialize type is expecting an i128 value. Read more
Sourceยง

fn deserialize_u8<V>( self, visitor: V, ) -> Result<<V as Visitor<'de>>::Value, Error>
where V: Visitor<'de>,

Hint that the Deserialize type is expecting a u8 value.
Sourceยง

fn deserialize_u16<V>( self, visitor: V, ) -> Result<<V as Visitor<'de>>::Value, Error>
where V: Visitor<'de>,

Hint that the Deserialize type is expecting a u16 value.
Sourceยง

fn deserialize_u32<V>( self, visitor: V, ) -> Result<<V as Visitor<'de>>::Value, Error>
where V: Visitor<'de>,

Hint that the Deserialize type is expecting a u32 value.
Sourceยง

fn deserialize_u64<V>( self, visitor: V, ) -> Result<<V as Visitor<'de>>::Value, Error>
where V: Visitor<'de>,

Hint that the Deserialize type is expecting a u64 value.
Sourceยง

fn deserialize_u128<V>( self, visitor: V, ) -> Result<<V as Visitor<'de>>::Value, Error>
where V: Visitor<'de>,

Hint that the Deserialize type is expecting an u128 value. Read more
Sourceยง

fn deserialize_f32<V>( self, visitor: V, ) -> Result<<V as Visitor<'de>>::Value, Error>
where V: Visitor<'de>,

Hint that the Deserialize type is expecting a f32 value.
Sourceยง

fn deserialize_f64<V>( self, visitor: V, ) -> Result<<V as Visitor<'de>>::Value, Error>
where V: Visitor<'de>,

Hint that the Deserialize type is expecting a f64 value.
Sourceยง

fn deserialize_char<V>( self, visitor: V, ) -> Result<<V as Visitor<'de>>::Value, Error>
where V: Visitor<'de>,

Hint that the Deserialize type is expecting a char value.
Sourceยง

fn deserialize_str<V>( self, visitor: V, ) -> Result<<V as Visitor<'de>>::Value, Error>
where V: Visitor<'de>,

Hint that the Deserialize type is expecting a string value and does not benefit from taking ownership of buffered data owned by the Deserializer. Read more
Sourceยง

fn deserialize_string<V>( self, visitor: V, ) -> Result<<V as Visitor<'de>>::Value, Error>
where V: Visitor<'de>,

Hint that the Deserialize type is expecting a string value and would benefit from taking ownership of buffered data owned by the Deserializer. Read more
Sourceยง

fn deserialize_bytes<V>( self, visitor: V, ) -> Result<<V as Visitor<'de>>::Value, Error>
where V: Visitor<'de>,

Hint that the Deserialize type is expecting a byte array and does not benefit from taking ownership of buffered data owned by the Deserializer. Read more
Sourceยง

fn deserialize_byte_buf<V>( self, visitor: V, ) -> Result<<V as Visitor<'de>>::Value, Error>
where V: Visitor<'de>,

Hint that the Deserialize type is expecting a byte array and would benefit from taking ownership of buffered data owned by the Deserializer. Read more
Sourceยง

fn deserialize_option<V>( self, visitor: V, ) -> Result<<V as Visitor<'de>>::Value, Error>
where V: Visitor<'de>,

Hint that the Deserialize type is expecting an optional value. Read more
Sourceยง

fn deserialize_unit<V>( self, visitor: V, ) -> Result<<V as Visitor<'de>>::Value, Error>
where V: Visitor<'de>,

Hint that the Deserialize type is expecting a unit value.
Sourceยง

fn deserialize_unit_struct<V>( self, name: &'static str, visitor: V, ) -> Result<<V as Visitor<'de>>::Value, Error>
where V: Visitor<'de>,

Hint that the Deserialize type is expecting a unit struct with a particular name.
Sourceยง

fn deserialize_newtype_struct<V>( self, name: &'static str, visitor: V, ) -> Result<<V as Visitor<'de>>::Value, Error>
where V: Visitor<'de>,

Hint that the Deserialize type is expecting a newtype struct with a particular name.
Sourceยง

fn deserialize_seq<V>( self, visitor: V, ) -> Result<<V as Visitor<'de>>::Value, Error>
where V: Visitor<'de>,

Hint that the Deserialize type is expecting a sequence of values.
Sourceยง

fn deserialize_tuple<V>( self, len: usize, visitor: V, ) -> Result<<V as Visitor<'de>>::Value, Error>
where V: Visitor<'de>,

Hint that the Deserialize type is expecting a sequence of values and knows how many values there are without looking at the serialized data.
Sourceยง

fn deserialize_tuple_struct<V>( self, name: &'static str, len: usize, visitor: V, ) -> Result<<V as Visitor<'de>>::Value, Error>
where V: Visitor<'de>,

Hint that the Deserialize type is expecting a tuple struct with a particular name and number of fields.
Sourceยง

fn deserialize_map<V>( self, visitor: V, ) -> Result<<V as Visitor<'de>>::Value, Error>
where V: Visitor<'de>,

Hint that the Deserialize type is expecting a map of key-value pairs.
Sourceยง

fn deserialize_struct<V>( self, name: &'static str, fields: &'static [&'static str], visitor: V, ) -> Result<<V as Visitor<'de>>::Value, Error>
where V: Visitor<'de>,

Hint that the Deserialize type is expecting a struct with a particular name and fields.
Sourceยง

fn deserialize_enum<V>( self, name: &'static str, variants: &'static [&'static str], visitor: V, ) -> Result<<V as Visitor<'de>>::Value, Error>
where V: Visitor<'de>,

Hint that the Deserialize type is expecting an enum value with a particular name and possible variants.
Sourceยง

fn deserialize_identifier<V>( self, visitor: V, ) -> Result<<V as Visitor<'de>>::Value, Error>
where V: Visitor<'de>,

Hint that the Deserialize type is expecting the name of a struct field or the discriminant of an enum variant.
Sourceยง

fn deserialize_ignored_any<V>( self, visitor: V, ) -> Result<<V as Visitor<'de>>::Value, Error>
where V: Visitor<'de>,

Hint that the Deserialize type needs to deserialize a value whose type doesnโ€™t matter because it is ignored. Read more
Sourceยง

fn is_human_readable(&self) -> bool

Determine whether Deserialize implementations should expect to deserialize their human-readable form. Read more
Sourceยง

impl Display for RawValue

Sourceยง

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

Formats the value using the given formatter. Read more
Sourceยง

impl From<Box<RawValue>> for Box<str>

Sourceยง

fn from(raw_value: Box<RawValue>) -> Box<str>

Converts to this type from the input type.
Sourceยง

impl<'de> IntoDeserializer<'de, Error> for &'de RawValue

Sourceยง

type Deserializer = &'de RawValue

The type of the deserializer being converted into.
Sourceยง

fn into_deserializer( self, ) -> <&'de RawValue as IntoDeserializer<'de, Error>>::Deserializer

Convert this value into a deserializer.
Sourceยง

impl PgHasArrayType for RawValue

Sourceยง

impl Serialize for RawValue

Sourceยง

fn serialize<S>( &self, serializer: S, ) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error>
where S: Serializer,

Serialize this value into the given Serde serializer. Read more
Sourceยง

impl ToOwned for RawValue

Sourceยง

type Owned = Box<RawValue>

The resulting type after obtaining ownership.
Sourceยง

fn to_owned(&self) -> <RawValue as ToOwned>::Owned

Creates owned data from borrowed data, usually by cloning. Read more
1.63.0 ยท Sourceยง

fn clone_into(&self, target: &mut Self::Owned)

Uses borrowed data to replace owned data, usually by cloning. Read more
Sourceยง

impl<DB> Type<DB> for RawValue
where Json<&'a RawValue>: for<'a> Type<DB>, DB: Database,

Sourceยง

fn type_info() -> <DB as Database>::TypeInfo

Returns the canonical SQL type for this Rust type. Read more
Sourceยง

fn compatible(ty: &<DB as Database>::TypeInfo) -> bool

Determines if this Rust type is compatible with the given SQL type. Read more

Auto Trait Implementationsยง

Blanket Implementationsยง

Sourceยง

impl<T> Any for T
where T: 'static + ?Sized,

Sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Sourceยง

impl<T> Borrow<T> for T
where T: ?Sized,

Sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Sourceยง

impl<T> BorrowMut<T> for T
where T: ?Sized,

Sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Sourceยง

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Sourceยง

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Sourceยง

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Sourceยง

impl<T> ToString for T
where T: Display + ?Sized,

Sourceยง

fn to_string(&self) -> String

Converts the given value to a String. Read more