Skip to content

Provide an infallible ToJson trait in a separate crate #327

Open
@dtolnay

Description

@dtolnay

I would like an infallible JSON value conversion crate. Basically rustc_serialize::json::ToJson but for serde_json::Value.

With serde_json::to_value you get a fallible conversion that may fail for example because the input is a mutex that is poisoned, or because the input is a map with non-string keys, or for any number of other reasons. In some situations you want the type system to guarantee that the conversion cannot fail in those ways.

An infallible conversion would require its own custom derive. Something like:

#[derive(ToJson)]
struct S<T> {
    a: String,
    b: T,
}

// expands to
impl<T> ToJson for S<T> where T: ToJson {
    fn to_json(&self) -> serde_json::Value {
        let mut map = serde_json::Map::with_capacity(2);
        map.insert("a", self.a.to_json());
        map.insert("b", self.b.to_json());
        serde_json::Value::Object(map)
    }
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions