Is there a way to convert a Cerd card to a value?
According to the Serde spec, Object
/ Map<String, Value>
is Value
:
pub enum Value {
Null,
Bool(bool),
Number(Number),
String(String),
Array(Vec<Value>),
Object(Map<String, Value>),
}
But when I compile this code:
extern crate serde;
#[macro_use]
extern crate serde_json;
#[derive(Debug)]
struct Wrapper {
ok: bool,
data: Option<serde_json::Value>,
}
impl Wrapper {
fn ok() -> Wrapper {
Wrapper {
ok: true,
data: None,
}
}
pub fn data(&mut self, data: serde_json::Value) -> &mut Wrapper {
self.data = Some(data);
self
}
pub fn finalize(self) -> Wrapper {
self
}
}
trait IsValidWrapper {
fn is_valid_wrapper(&self) -> bool;
}
impl IsValidWrapper for serde_json::Map<std::string::String, serde_json::Value> {
fn is_valid_wrapper(&self) -> bool {
self["ok"].as_bool().unwrap_or(false)
}
}
fn main() {
let json = json!({
"name": "John Doe",
"age": 43,
"phones": [
"+44 1234567",
"+44 2345678"
]
});
let converted_json: Wrapper = json
.as_object()
.map_or_else(
|| Err(json),
|obj| {
if obj.is_valid_wrapper() {
Ok(Wrapper::ok().data(obj["data"].clone()).finalize())
} else {
Err(*obj as serde_json::Value)
}
},
)
.unwrap_or_else(|data| Wrapper::ok().data(data.clone()).finalize());
println!(
"org json = {:?} => converted json = {:?}",
json, converted_json
);
}
I am getting this error:
error[E0605]: non-primitive cast: `serde_json::Map<std::string::String, serde_json::Value>` as `serde_json::Value` --> src/main.rs:60:25 | 60 | Err(*obj as serde_json::Value) | ^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: an `as` expression can only be used to convert between primitive types. Consider using the `From` trait
Is there a way to dump a Map
into Value
?
source to share
a
Object
/Map<String, Value>
isValue
No, it is not. Value
- a type. Map<String, Value>
is the type. Value::Object
is an enumeration variant that is not a separate type. In this case, Value::Object
contains a different type value Map<String, Value>
. You must wrap the value in a variant in order to convert the type:
Err(serde_json::Value::Object(obj))
This will lead to a problem:
error[E0308]: mismatched types --> src/main.rs:57:55 | 57 | Err(serde_json::Value::Object(obj)) | ^^^ expected struct `serde_json::Map`, found reference | = note: expected type `serde_json::Map<std::string::String, serde_json::Value>` found type `&serde_json::Map<std::string::String, serde_json::Value>`
as_object
returns a reference to the contained object (if present), not the value itself. You will need match
on it:
let converted_json = match json { serde_json::Value::Object(obj) => {} _ => {} };
Something like that:
let converted_json = match json {
serde_json::Value::Object(obj) => {
if obj.is_valid_wrapper() {
let mut w = Wrapper::ok();
w.data(obj["data"].clone());
Ok(w.finalize())
} else {
Err(serde_json::Value::Object(obj))
}
}
other => Err(other),
};
source to share