json_in_type icon indicating copy to clipboard operation
json_in_type copied to clipboard

Optional field support in json_object! macro

Open ilammy opened this issue 4 years ago • 0 comments

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:

  • foo
  • foo, baz
  • foo, bar
  • foo, 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.

  1. Computed optional keys:

     json_object! {
         (maybe_key): value,
     }
    

    where maybe_key is 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.

  2. Skip fields by Option values:

     json_object! {
         key?: maybe_value,
     }
    

    where maybe_value is 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.

ilammy avatar Apr 07 '21 03:04 ilammy