From 8e1f7e5f9dfac4c79c6a4294e112c7882e783e09 Mon Sep 17 00:00:00 2001 From: Dnomd343 Date: Mon, 31 Oct 2022 22:26:49 +0800 Subject: [PATCH] update: framework of to-json --- to-json/src/main.rs | 74 +++++++++++++++++++++++++++++++++++++++------ 1 file changed, 64 insertions(+), 10 deletions(-) diff --git a/to-json/src/main.rs b/to-json/src/main.rs index 4252260..c6a2e85 100644 --- a/to-json/src/main.rs +++ b/to-json/src/main.rs @@ -1,6 +1,5 @@ -use serde_json::Value as JsonValue; -use serde_yaml::Value as YamlValue; -use toml::Value as TomlValue; +use serde_json as json; +use serde_yaml as yaml; const JSON_STR: &str = r#" { @@ -29,6 +28,37 @@ author = "dnomd343" test = [ 123, 234, 345 ] "#; +#[derive(Debug)] +enum Format { + JSON(json::Value), + YAML(yaml::Value), + TOML(toml::Value), +} + +fn parser(raw: &str) -> Option { + if let Ok(data) = json::from_str::(raw) { // try JSON format + return Some(Format::JSON(data)); + } + if let Ok(data) = toml::from_str::(raw) { // try TOML format + return Some(Format::TOML(data)); + } + if let Ok(data) = yaml::from_str::(raw) { // try YAML format + return Some(Format::YAML(data)); + } + return None; +} + +fn to_json(raw: &str) -> String { + match parser(raw) { + Some(data) => match data { + Format::JSON(dat) => json::to_string(&dat).unwrap(), + Format::YAML(dat) => json::to_string(&dat).unwrap(), + Format::TOML(dat) => json::to_string(&dat).unwrap(), + }, + None => std::process::exit(1), + } +} + fn main() { println!("---------------------------------"); println!("JSON raw content:\n{}", JSON_STR); @@ -38,13 +68,37 @@ fn main() { println!("TOML raw content:\n{}", TOML_STR); println!("---------------------------------"); - // let data: JsonValue = serde_json::from_str(JSON_STR).unwrap(); - // println!("{:#?}", data); - // let data: YamlValue = serde_yaml::from_str(YAML_STR).unwrap(); + let temp = to_json(JSON_STR); + println!("{}", temp); + + // let a = String::from("ok"); + // match parser(JSON_STR) { + // Some(data) => { + // // println!("{:#?}", data); + // match data { + // Format::JSON(dat) => { + // return json::to_string(&data).unwrap() + // }, + // _ => println!("123"), + // // Format::JSON(dat) => println!("{:#?}", dat), + // // Format::YAML(dat) => println!("{:#?}", dat), + // // Format::TOML(dat) => println!("{:#?}", dat), + // } + // // let temp = data; + // // let ret = json::to_string(&data).unwrap(); + // // println!("JSON output ->\n{}", ret); + // }, + // None => println!("parser error"), + // } + + // let data = parser(JSON_STR); // println!("{:#?}", data); - let data: TomlValue = toml::from_str(TOML_STR).unwrap(); - println!("{:#?}", data); - let ret = serde_json::to_string(&data).unwrap(); - println!("JSON output ->\n{}", ret); + // decode(YAML_STR); + // decode(TOML_STR); + + + + // let ret = serde_json::to_string(&data).unwrap(); + // println!("JSON output ->\n{}", ret); }