1

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)
ryah
  • 11
  • 1

1 Answers1

3

An iterator that returns two-element tuples can be collected 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.

Joe Clay
  • 33,401
  • 4
  • 85
  • 85