Optional field support in json_object! macro
I've quite enjoyed json_in_type being faster at JSON serialization than serde. Thanks a lot for creating this crate!
Though, there were some itches that required scratching. One of them is optional field support in json_object! macro. It's possible to compute field keys with the following syntax:
json_object! {
[computed_key]: value,
}
but it's currently not possible to serialize optional fields nicely. Suppose you have
{
"foo": 123,
"bar": 456,
"baz": 789
}
where bar and baz can be optional and not included into the object. With json_object! the only option you have right now is to encode all four object variants explicitly:
foofoo,bazfoo,barfoo,bar,baz
I have a private fork of json_in_type which adds the following features to json_object! macro that make the above possible.
-
Computed optional keys:
json_object! { (maybe_key): value, }where
maybe_keyis an Option with key name. If the key is None, it's skipped. Otherwise the Some value is used. This thing was useful to produce minified JSON with optional fields. -
Skip fields by Option values:
json_object! { key?: maybe_value, }where
maybe_valueis an Option. If it's None, the field is skipped from JSON form. Otherwise it's included.
What do you think about this?
I realize that those approaches might not be the best for everyone. Consider this a start of the discussion about how it might look like.