How to do it...

  1. Open the Cargo.toml file that was generated earlier for you

  2. Under [dependencies], if you haven't done so already, add the following line:
serde_json = "1.0.8"
  1. If you want, you can go to the serde_json crates.io web page (https://crates.io/crates/serde_json) to check for the newest version and use that one instead
  2. In the bin folder, create a file called dynamic_json.rs

  3. Add the following code and run it with cargo run --bin dynamic_json:

1    #[macro_use] 
2 extern crate serde_json;
3
4 use std::io::{self, BufRead};
5 use std::collections::HashMap;
6
7 fn main() {
8 // A HashMap is the same as a JSON without any schema
9 let mut key_value_map = HashMap::new();
10 let stdin = io::stdin();
11 println!("Enter a key and a value");
12 for input in stdin.lock().lines() {
13 let input = input.expect("Failed to read line");
14 let key_value: Vec<_> = input.split_whitespace().collect();
15 let key = key_value[0].to_string();
16 let value = key_value[1].to_string();
17
18 println!("Saving key-value pair: {} -> {}", key, value);
19 // The json! macro lets us convert a value into its JSON
representation
20 key_value_map.insert(key, json!(value));
21 println!(
22 "Enter another pair or stop by pressing '{}'",
23 END_OF_TRANSMISSION
24 );
25 }
26 // to_string_pretty returns a JSON with nicely readable
whitespace
27 let json =
28 serde_json::to_string_pretty(&key_value_map).expect("Failed
to convert HashMap into JSON");
29 println!("Your input has been made into the following
JSON:");
30 println!("{}", json);
31 }
32
33 #[cfg(target_os = "windows")]
34 const END_OF_TRANSMISSION: &str = "Ctrl Z";
35
36 #[cfg(not(target_os = "windows"))]
37 const END_OF_TRANSMISSION: &str = "Ctrl D";
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.104.95