Reputation: 2239
I am using the the Rust libraries swtweb (to interface with JavaScript) and serde-json (to work with JSON). Both have a Value
type to represent JavaScript objects that are very similar:
#[derive(Clone, PartialEq, Debug)]
pub enum Value {
Undefined,
Null,
Bool(bool),
Number(Number),
Symbol(Symbol),
String(String),
Reference(Reference)
}
and serde-json's Value
:
#[derive(Clone, PartialEq)]
pub enum Value {
Null,
Bool(bool),
Number(Number),
String(String),
Array(Vec<Value>),
Object(Map<String, Value>),
}
What is an approach to transform instances of one type to another? Is it possible to derive a common trait without modifying the libraries?
Upvotes: 0
Views: 466
Reputation: 733
Looking at the doc of stdweb::Value
, it seems they have you covered!
It implements TryFrom<JsonValue>
, with JsonValue
being an alias of serde_json::Value
, so this lets you converts from serde_json::Value
to stdweb::Value
.
It implements Serialize
, and serde_json::to_value
lets you convert any type that implements Serialize
to a serde_json::Value
So this should work:
let json_value: serde_json::Value = json!("my value");
println!("{:#?}", json_value);
let stdweb_value: stdweb::Value = stdweb::Value::try_from(json_value).unwrap();
println!("{:#?}", stdweb_value);
let json_value_again: serde_json::Value = serde_json::to_value(stdweb_value).unwrap();
println!("{:#?}", json_value_again);
Upvotes: 1