pub fn to_value<T>(value: &T) -> Result<Value>
Expand description
Convert a T
into sonic_rs::Value
which can represent any valid JSON data.
§Example
use serde::Serialize;
use sonic_rs::{json, to_value, Value};
#[derive(Serialize, Debug)]
struct User {
string: String,
number: i32,
array: Vec<String>,
}
let user = User{
string: "hello".into(),
number: 123,
array: vec!["a".into(), "b".into(), "c".into()],
};
let got: Value = sonic_rs::to_value(&user).unwrap();
let expect = json!({
"string": "hello",
"number": 123,
"array": ["a", "b", "c"],
});
assert_eq!(got, expect);
§Errors
This conversion can fail if T
’s implementation of Serialize
decides to
fail, or if T
contains a map with non-string keys.
use std::collections::BTreeMap;
use sonic_rs::to_value;
// The keys in this map are vectors, not strings.
let mut map = BTreeMap::new();
map.insert(vec![32, 64], "x86");
let err = to_value(&map).unwrap_err().to_string();
assert!(err.contains("Expected the key to be string/bool/number when serializing map"));