Skip to content

Commit e6a162e

Browse files
committed
Rust lbr-prelude: add to_json_string and from_json_string trait methods
1 parent 17813f9 commit e6a162e

File tree

2 files changed

+15
-0
lines changed

2 files changed

+15
-0
lines changed

runtimes/rust/lbr-prelude/src/error.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,8 @@ impl From<&Value> for JsonType {
2929
/// Error type representing Json conversion errors
3030
#[derive(thiserror::Error, Debug)]
3131
pub enum Error {
32+
#[error("Malformed JSON string, unable to parse")]
33+
MalformedJson,
3234
#[error("{parser:?} > Expected a JSON type: {wanted:?}, but got a JSON type: {got:?}")]
3335
UnexpectedJsonType {
3436
got: JsonType,

runtimes/rust/lbr-prelude/src/json.rs

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,19 @@ pub trait Json {
1818
fn from_json(value: &Value) -> Result<Self, Error>
1919
where
2020
Self: Sized;
21+
22+
fn to_json_string(&self) -> String {
23+
self.to_json().to_string()
24+
}
25+
26+
fn from_json_string(string: &str) -> Result<Self, Error>
27+
where
28+
Self: Sized,
29+
{
30+
Value::from_str(string)
31+
.map_err(|_| Error::MalformedJson)
32+
.and_then(|value| Self::from_json(&value))
33+
}
2134
}
2235

2336
// lbf-prelude::json instance rule implementations

0 commit comments

Comments
 (0)