From: Martin Pitt Date: Sat, 25 Sep 2021 08:20:01 +0000 (+0200) Subject: serde: Write JSON to file X-Git-Url: https://piware.de/gitweb/?a=commitdiff_plain;h=c90073a9f013cde0cbf84fa43f986f6c74d38168;p=learn-rust.git serde: Write JSON to file --- diff --git a/serde/src/main.rs b/serde/src/main.rs index 0c9efe9..1357100 100644 --- a/serde/src/main.rs +++ b/serde/src/main.rs @@ -1,3 +1,4 @@ +use std::fs; use serde::{Serialize, Deserialize}; #[derive(Serialize, Deserialize, Debug)] @@ -29,6 +30,8 @@ fn create_contacts() { // FIXME: Use ? and return Result let serialized = serde_json::to_string(&contacts).unwrap(); println!("serialized: {}", serialized); + let mut f = fs::File::create("/tmp/contacts.json").unwrap_or_else(|e| panic!("Could not create /tmp/contacts.json: {:?}", e)); + serde_json::to_writer_pretty(&mut f, &contacts).unwrap_or_else(|e| panic!("Could not serialize contacts: {:?}", e)); } fn main() {