Created
October 16, 2024 19:54
-
-
Save dacr/4abf9bc1894365b6c40338d5e873c0c5 to your computer and use it in GitHub Desktop.
rust hello json / published by https://github.com/dacr/code-examples-manager #0cc4ba7f-8c56-494e-ad8d-42b0e69b6d4c/fe5a75681231f19dfa7e091f82d35249cb02c611
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env rust-script | |
//! ```cargo | |
//! [dependencies] | |
//! serde= { version = "1.0.210", features = ["derive"] } | |
//! serde_json = "1.0.128" | |
//! ``` | |
// summary : rust hello json | |
// keywords : rust, dependencies, @testable | |
// publish : gist | |
// authors : David Crosson | |
// license : Apache NON-AI License Version 2.0 (https://raw.githubusercontent.com/non-ai-licenses/non-ai-licenses/main/NON-AI-APACHE2) | |
// id : 0cc4ba7f-8c56-494e-ad8d-42b0e69b6d4c | |
// created-on : 2024-10-16T21:12:55+02:00 | |
// managed-by : https://github.com/dacr/code-examples-manager | |
// run-with : ./$file | |
use serde::{Deserialize, Serialize}; | |
use serde_json::Result; | |
#[derive(Debug)] | |
#[derive(Serialize, Deserialize)] | |
struct Person { | |
first_name: String, | |
last_name: String, | |
age: u8, | |
phones: Vec<String>, | |
} | |
fn main() { | |
let data = r#" | |
{ | |
"last_name": "Doe", | |
"first_name": "John", | |
"age": 42, | |
"phones": [ | |
"+33 12 34 56 78", | |
"+33 98 76 54 32" | |
] | |
} | |
"#; | |
let rp: Result<Person> = serde_json::from_str(data); | |
match rp { | |
Ok(p) => { | |
println!("parsed json {:?}", p); | |
let j: serde_json::Result<String> = serde_json::to_string(&p); | |
j.iter().for_each(|json| println!("generated json {}", json)); | |
} | |
Err(e) => { | |
println!("Parsing error {}", e); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment