serdejsonany_key

Workaround for \"key must be a string\" error with serde_json. Serialize any HashMap, Vec, Iter<(&K,&V)>, or Iter<&(K,V)> as a JSON map. The output will be the same as if you manually serialized the struct key to a string.

Also supports deserialization to HashMap or Vec<(K,V)>.

Example

```rust use std::collections::HashMap; use serde::{Serialize, Deserialize}; use serdejsonany_key::*;

[derive(Clone, Copy, Deserialize, Serialize, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]

pub struct Test { pub a: i32, pub b: i32 }

fn main() { let mut map = HashMap::::new(); map.insert(Test {a: 3, b: 5}, Test {a: 7, b: 9});

// Fails with error: key must be a string let serialized = serdejson::tostring(&map); match serialized { Ok(serialized) => { println!("{}", serialized); } Err(e) => { println!("Error as expected: {}", e); } }

// Long winded workaround that copies the map // Prints {"{\"a\":3,\"b\":5}":{"a":7,"b":9}} let stringmap: HashMap = map.iter().map(|(k, &v)| (serdejson::tostring(k).unwrap(), v)).collect(); let serialized = serdejson::tostring(&stringmap).unwrap(); println!("{}", serialized);

// Use this crate's utility function - elements are serialized lazily // Same output let serialized = serdejsonanykey::mapto_json(&map).unwrap(); println!("{}", serialized);

// Utility function also exists for vec of tuples // Same output let vec = vec![(Test {a: 3, b: 5}, Test {a: 7, b: 9})]; let serialized = serdejsonanykey::vecto_json(&vec).unwrap(); println!("{}", serialized);

// Also supports any other data type that generates an Iter<&(K,V)> or Iter<(&K, &V)> // Same output let mut btree = std::collections::BTreeMap::::new(); btree.insert(Test {a: 3, b: 5}, Test {a: 7, b: 9}); let serialized = serdejsonanykey::mapitertojson(&mut btree.iter()).unwrap(); println!("{}", serialized);

// Also supports deserialization, back to HashMap or Vec let deserializedmap: HashMap = serdejsonanykey::jsontomap(&serialized).unwrap(); asserteq!(map, deserializedmap); let deserializedvec: Vec<(Test,Test)> = serdejsonanykey::jsontovec(&serialized).unwrap(); asserteq!(vec, deserializedvec); } ```

Output: Error as expected: key must be a string {"{\"a\":3,\"b\":5}":{"a":7,"b":9}} {"{\"a\":3,\"b\":5}":{"a":7,"b":9}} {"{\"a\":3,\"b\":5}":{"a":7,"b":9}} {"{\"a\":3,\"b\":5}":{"a":7,"b":9}}