How can I use serde_json to serialize std::env::vars()
The following works but I feel like it could be done better:
let mut vars = std::collections::HashMap::new();
for (key, value) in std::env::vars() {
vars.insert(key, value);
}
json!(vars)
How can I use serde_json to serialize std::env::vars()
The following works but I feel like it could be done better:
let mut vars = std::collections::HashMap::new();
for (key, value) in std::env::vars() {
vars.insert(key, value);
}
json!(vars)
An iterator that returns two-element tuples can be collect
ed into a new HashMap
. std::env::vars
returns such an iterator (called Vars
), so that will work here:
let vars: HashMap<String, String> = std::env::vars().collect();
json!(vars)
Beyond that, you can't really simplify things any further without Serialize
being directly implemented for Vars
. Since Vars
is a standard library type, and the Serialize
trait comes from an external crate, you can't do this.