Skip to content

Commit 169a895

Browse files
committed
Add value::to_raw_value
1 parent cb17821 commit 169a895

File tree

2 files changed

+61
-1
lines changed

2 files changed

+61
-1
lines changed

src/raw.rs

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -215,6 +215,66 @@ impl RawValue {
215215
}
216216
}
217217

218+
/// Convert a `T` into a boxed `RawValue`.
219+
///
220+
/// # Example
221+
///
222+
/// ```
223+
/// // Upstream crate
224+
/// # #[derive(Serialize)]
225+
/// pub struct Thing {
226+
/// foo: String,
227+
/// bar: Option<String>,
228+
/// extra_data: Box<RawValue>,
229+
/// }
230+
///
231+
/// // Local crate
232+
/// use serde::Serialize;
233+
/// use serde_json::value::{to_raw_value, RawValue};
234+
///
235+
/// #[derive(Serialize)]
236+
/// struct MyExtraData {
237+
/// a: u32,
238+
/// b: u32,
239+
/// }
240+
///
241+
/// let my_thing = Thing {
242+
/// foo: "FooVal".into(),
243+
/// bar: None,
244+
/// extra_data: to_raw_value(&MyExtraData { a: 1, b: 2 }).unwrap(),
245+
/// };
246+
/// # assert_eq!(
247+
/// # serde_json::to_value(my_thing).unwrap(),
248+
/// # serde_json::json!({
249+
/// # "foo": "FooVal",
250+
/// # "bar": null,
251+
/// # "extra_data": { "a": 1, "b": 2 }
252+
/// # })
253+
/// # );
254+
/// ```
255+
///
256+
/// # Errors
257+
///
258+
/// This conversion can fail if `T`'s implementation of `Serialize` decides to
259+
/// fail, or if `T` contains a map with non-string keys.
260+
///
261+
/// ```
262+
/// use std::collections::BTreeMap;
263+
///
264+
/// // The keys in this map are vectors, not strings.
265+
/// let mut map = BTreeMap::new();
266+
/// map.insert(vec![32, 64], "x86");
267+
///
268+
/// println!("{}", serde_json::value::to_raw_value(&map).unwrap_err());
269+
/// ```
270+
pub fn to_raw_value<T>(value: &T) -> Result<Box<RawValue>, Error>
271+
where
272+
T: Serialize,
273+
{
274+
let json_string = crate::to_string(value)?;
275+
Ok(RawValue::from_owned(json_string.into_boxed_str()))
276+
}
277+
218278
pub const TOKEN: &str = "$serde_json::private::RawValue";
219279

220280
impl Serialize for RawValue {

src/value/mod.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,7 @@ pub use crate::map::Map;
102102
pub use crate::number::Number;
103103

104104
#[cfg(feature = "raw_value")]
105-
pub use crate::raw::RawValue;
105+
pub use crate::raw::{to_raw_value, RawValue};
106106

107107
/// Represents any valid JSON value.
108108
///

0 commit comments

Comments
 (0)