MCPcopy Create free account
hub / github.com/cel-rust/cel-rust / json

Method json

cel/src/json.rs:36–67  ·  view source on GitHub ↗

Converts a CEL value to a JSON value. # Example ``` use cel::{Context, Program}; let program = Program::compile("null").unwrap(); let value = program.execute(&Context::default()).unwrap(); let result = value.json().unwrap(); assert_eq!(result, serde_json::Value::Null); ```

(&self)

Source from the content-addressed store, hash-verified

34 /// assert_eq!(result, serde_json::Value::Null);
35 /// ```
36 pub fn json(&self) -> Result<serde_json::Value, ConvertToJsonError<'_>> {
37 Ok(match *self {
38 Value::List(ref vec) => serde_json::Value::Array(
39 vec.iter()
40 .map(|v| v.json())
41 .collect::<Result<Vec<_>, _>>()?,
42 ),
43 Value::Map(ref map) => {
44 let mut obj = serde_json::Map::new();
45 for (k, v) in map.map.iter() {
46 obj.insert(k.to_string(), v.json()?);
47 }
48 serde_json::Value::Object(obj)
49 }
50 Value::Int(i) => i.into(),
51 Value::UInt(u) => u.into(),
52 Value::Float(f) => f.into(),
53 Value::String(ref s) => s.to_string().into(),
54 Value::Bool(b) => b.into(),
55 Value::Bytes(ref b) => BASE64_STANDARD.encode(b.as_slice()).to_string().into(),
56 Value::Null => serde_json::Value::Null,
57 #[cfg(feature = "chrono")]
58 Value::Timestamp(ref dt) => dt.to_rfc3339().into(),
59 #[cfg(feature = "chrono")]
60 Value::Duration(ref v) => serde_json::Value::Number(serde_json::Number::from(
61 v.num_nanoseconds()
62 .ok_or(ConvertToJsonError::DurationOverflow(v))?,
63 )),
64 Value::Opaque(ref opaque) => (**opaque).json().unwrap_or(serde_json::Value::Null),
65 _ => return Err(ConvertToJsonError::Value(self)),
66 })
67 }
68}
69
70#[cfg(test)]

Callers 1

mainFunction · 0.45

Calls 3

ValueEnum · 0.85
mapMethod · 0.80
iterMethod · 0.45

Tested by

no test coverage detected