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.tomlfile 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_jsoncrates.io web page (https://crates.io/crates/serde_json) to check for the newest version and use that one instead In the
binfolder, create a file calleddynamic_json.rsAdd 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...