Skip to content

Commit

Permalink
feat: recursive print
Browse files Browse the repository at this point in the history
  • Loading branch information
LorenzoLeonardo committed Apr 1, 2024
1 parent d65091d commit 90e72d2
Show file tree
Hide file tree
Showing 2 changed files with 82 additions and 0 deletions.
29 changes: 29 additions & 0 deletions src/jsonelem.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,35 @@ impl JsonElem {
let val: T = serde_json::from_str(&val).map_err(Error::SerdeJson)?;
Ok(val)
}

pub fn print(&self, indent: usize) {
print!("result : ");
self.print_recursive(indent);
}

fn print_recursive(&self, indent: usize) {
match self {
JsonElem::Null => println!("null"),
JsonElem::Bool(b) => println!(": b {}", b),
JsonElem::Integer(n) => println!(": i {}", n),
JsonElem::String(s) => println!(": {}", s),
JsonElem::Vec(arr) => {
println!("List");
for (n, element) in arr.iter().enumerate() {
print!("{}{}", " ".repeat(indent + 2), n);
element.print_recursive(indent + 2);
}
}
JsonElem::Float(f) => println!(": f {}", f),
JsonElem::HashMap(obj) => {
println!("Map");
for (key, val) in obj.iter() {
print!("{}{} : ", " ".repeat(indent + 2), key);
val.print_recursive(indent + 2);
}
}
}
}
}

/// Converts from String to JsonElem
Expand Down
53 changes: 53 additions & 0 deletions src/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -358,3 +358,56 @@ fn test_null() {

assert_eq!(call, output);
}

#[test]
fn test_recursive_print() {
#[derive(Serialize, Deserialize, Debug, PartialEq)]
struct Provider {
year: i32,
process: String,
provider: String,
authorization_endpoint: String,
token_endpoint: String,
device_auth_endpoint: String,
scopes: Vec<String>,
client_id: String,
#[serde(skip_serializing_if = "Option::is_none")]
client_secret: Option<String>,
client_map: HashMap<String, JsonElem>,
}

let mut hash = HashMap::new();
hash.insert(
"key1".into(),
JsonElem::Vec(vec![
JsonElem::String("test val".to_string()),
JsonElem::Bool(true),
JsonElem::Integer(123456789),
JsonElem::Float(12345.6789),
]),
);
let given = Provider {
year: 2024,
process: String::from("process name"),
provider: String::from("provider name"),
authorization_endpoint: String::from(
"https://login.microsoftonline.com/common/oauth2/v2.0/authorize",
),
token_endpoint: String::from("https://login.microsoftonline.com/common/oauth2/v2.0/token"),
device_auth_endpoint: String::from(
"https://login.microsoftonline.com/common/oauth2/v2.0/devicecode",
),
scopes: vec![
String::from("offline_access"),
String::from("https://outlook.office.com/SMTP.Send"),
String::from("https://outlook.office.com/User.Read"),
],
client_id: String::from("client-id-12345"),
client_secret: Some(String::from("secret-12345")),
client_map: hash,
};

let result = JsonElem::convert_from(&given).unwrap();

result.print(0);
}

0 comments on commit 90e72d2

Please sign in to comment.