Skip to content

Modify Json Decoder to handle missing/optional Json fields if mapped to Option  #12794

Closed
@quux00

Description

@quux00

Currently, the Json Decoder fails if the JSON it is decoding lacks a field in the Decodable struct it is mapping onto.

I propose that if a struct field maps to an Option, the Json Decoder would handle missing fields by mapping None to the field.

Here's a code example:

extern crate serialize;

#[deriving(Decodable)]
pub struct LogEntry {
    index: u64,
    term: u64,
    command_name: ~str,
    command: Option<~str>,  // optional in the JSON
}

#[cfg(test)]
mod test {
    use serialize::{json, Decodable};

    #[test]
    fn test_json_decode_of_LogEntry() {
        let jstr = ~r##"{"index": 200, "term": 4, "command_name": "foo"}"##;
        let jobj = json::from_str(jstr);

        let mut decoder = json::Decoder::new(jobj.unwrap());
        let decoded_obj: super::LogEntry = Decodable::decode(&mut decoder);  // fails

        assert_eq!(None, decoded_obj.command);
    }
}

This fails at runtime with the error message:

---- test::test_json_decode_of_LogEntry stdout ----
    task 'test::test_json_decode_of_LogEntry' failed at 'JSON decode error: missing required 'command' field in object: {}', /home/quux00/rustlang/rust/src/libserialize/json.rs:1128

I discussed this in the #rust IRC channel and cmr said this sounded reasonable when optional fields map to Option<> fields and suggested I file it here as a enhancement request.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions