Building JSON dynamically
When a JSON API is designed with a poorly-thought-out schema and inconsistent objects, you might end up with giant structures where most members are an Option
. If you find yourself only sending data to such a service, it might be a bit easier to dynamically build your JSON property by property.
How to do it...
Open the
Cargo.toml
file that was generated earlier for you- Under
[dependencies]
, if you haven't done so already, add the following line:
serde_json = "1.0.8"
- 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 In the
bin
folder, create a file calleddynamic_json.rs
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...