Skip to content
This repository has been archived by the owner on Dec 1, 2023. It is now read-only.

JSON serialization of Option types as HashMap keys is not round-trippable. #8

Closed
aatxe opened this issue Dec 31, 2014 · 3 comments
Closed

Comments

@aatxe
Copy link

aatxe commented Dec 31, 2014

Option types as HashMap keys is problematic when used with rustc-serialize. The issue is that if you use None as a key and try to serialize it, it will serialize to something like "null": /* value */. Note that this is the string null, and not the keyword null. As a result, when you try to decode it from JSON, you run into this issue: if you have an Option<String>, it'll decode as Some(null) instead of None. If you have a non-String type (e.g. u8), it will fail with an error. This issue is made more complex by the fact that there isn't a clear answer, at least that I can see, within the JSON specification. With the way HashMaps are encoded (as objects per the spec), the only valid key value is a string.

Here is the code where I encountered the issue. Here is an example of a HashMap<Option<String>, HashMap<Option<String>, uint>> being serialized:

{  
  "map": {  
    "I": {  
      "like":2
    },
    "null": {  
      "I":1
    },
    "dogs": {  
      "null":1
    },
    "cats": {  
      "and":1
    },
    "like": {  
      "cats":1,
      "dogs":1
    },
    "and": {  
      "I":1
    }
  }
}

All the "null" keys were originally None.

@oli-obk
Copy link
Contributor

oli-obk commented Jan 26, 2015

this is "obsolete" right now since Options aren't allowed as hash map keys anymore.

The following test passes.

    #[test]
    fn test_encode_hashmap_with_option_key() {
        use std::io::Writer;
        use std::collections::HashMap;
        use std::fmt;
        let mut hm = HashMap::new();
        hm.insert(Some("hi"), true);
        hm.insert(None, false);
        let mut mem_buf = Vec::new();
        let mut encoder = Encoder::new(&mut mem_buf as &mut fmt::Writer);
        let result = hm.encode(&mut encoder);
        match result.err().unwrap() {
            EncoderError::BadHashmapKey => (),
            _ => panic!("expected bad hash map key")
        }
    }

I don't see how Option<String> could ever be encoded safely and trivially comprehensible. Or even Something like Option<SomeEnumWithAVariantNamedNone>.

@oli-obk
Copy link
Contributor

oli-obk commented Jan 28, 2015

@alexcrichton Should this be closed or should a way be found to allow this?

@alexcrichton
Copy link
Contributor

Ah yes thanks @oli-obk! I think that Json just won't be able to encode all possible Rust types.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants