codetether_agent/tool/tetherscript/convert/
from_json.rs1use std::cell::RefCell;
2use std::rc::Rc;
3
4use serde_json::{Map, Number, Value};
5use tetherscript::value::Value as TetherScriptValue;
6
7pub fn json_to_tetherscript(value: Value) -> TetherScriptValue {
8 match value {
9 Value::Null => TetherScriptValue::Nil,
10 Value::Bool(value) => TetherScriptValue::Bool(value),
11 Value::Number(number) => number_to_tetherscript(number),
12 Value::String(value) => TetherScriptValue::Str(Rc::new(value)),
13 Value::Array(values) => TetherScriptValue::List(Rc::new(RefCell::new(
14 values.into_iter().map(json_to_tetherscript).collect(),
15 ))),
16 Value::Object(values) => object_to_tetherscript(values),
17 }
18}
19
20fn object_to_tetherscript(values: Map<String, Value>) -> TetherScriptValue {
21 TetherScriptValue::Map(Rc::new(RefCell::new(
22 values
23 .into_iter()
24 .map(|(key, value)| (key, json_to_tetherscript(value)))
25 .collect(),
26 )))
27}
28
29fn number_to_tetherscript(number: Number) -> TetherScriptValue {
30 if let Some(value) = number.as_i64() {
31 TetherScriptValue::Int(value)
32 } else if let Some(value) = number.as_u64() {
33 match i64::try_from(value) {
34 Ok(value) => TetherScriptValue::Int(value),
35 Err(_) => TetherScriptValue::Str(Rc::new(value.to_string())),
36 }
37 } else if let Some(value) = number.as_f64() {
38 TetherScriptValue::Float(value)
39 } else {
40 TetherScriptValue::Str(Rc::new(number.to_string()))
41 }
42}