1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
use crate::value::Value;
use crate::types::*;
impl Value {
pub fn cast_value_to_json(&self) -> Result<serde_json::Value, Box<dyn std::error::Error>> {
if self.dt == JSON {
return Err(format!("This Dynamic type is already json: {}", self.dt).into());
}
let ret = match self.dt {
INTEGER => {
match self.cast_int() {
Ok(int_value) => serde_json::json!(int_value),
Err(err) => {
return Err(format!("Error casting INTEGER: {}", err).into());
}
}
}
FLOAT => {
match self.cast_float() {
Ok(float_value) => serde_json::json!(float_value),
Err(err) => {
return Err(format!("Error casting FLOAT: {}", err).into());
}
}
}
BOOL => {
match self.cast_bool() {
Ok(bool_value) => serde_json::json!(bool_value),
Err(err) => {
return Err(format!("Error casting BOOL: {}", err).into());
}
}
}
NONE => {
serde_json::json!(null)
}
LIST => {
let mut res = serde_json::json!([]);
match self.cast_list() {
Ok(l_value) => {
for n in l_value {
match n.cast_value_to_json() {
Ok(j_value) => {
let Some(jres) = res.as_array_mut() else { return Err(format!("Error appending LIST").into()); };
jres.push(j_value);
}
Err(err) => {
return Err(format!("Error casting LIST: {}", err).into());
}
}
}
}
Err(err) => {
return Err(format!("Error casting LIST: {}", err).into());
}
}
res
}
MAP => {
let mut res = serde_json::json!({});
match self.cast_dict() {
Ok(m_value) => {
for k in m_value.keys() {
let v = match m_value.get(k) {
Some(v) => v,
None => return Err(format!("Error casting DICT").into()),
};
match v.cast_value_to_json() {
Ok(val) => {
res.as_object_mut().unwrap().insert(k.to_string(), val);
}
Err(err) => {
return Err(format!("Error casting DICT: {}", err).into());
}
}
}
}
Err(err) => {
return Err(format!("Error casting DICT: {}", err).into());
}
}
res
}
_ => return Err(format!("This Dynamic type is not supported for JSON: {}", self.dt).into()),
};
return Ok(ret);
}
}