ts-proto
ts-proto copied to clipboard
Optionally omit defaults in JSON
I'd really love a way of calling toJSON
that omits the defaults from the output. Ideally this would be an argument supplied to the toJSON
call because I have a use case for both.
-
Use Case 1: Snapshots In this use case I'd like to omit defaults to remove noise from Jest snapshots.
-
Use Case 2: Browser/Workshop Output In this use case I'd like to include defaults as it's easier when running a workshop if all defaults are included - rather than having to describe to attendees "oh, your attribute is not being set because it's the default"
Thus, my proposal would be that the signature for toJSON
would take an optional second parameter omitDefaults
which defaults to false (to maintain current behaviour).
This relates to this section in the docs;
When writing JSON,
ts-proto
currently does not normalize message when converting to JSON, other than omitting unset fields, but it may do so in the future.// Current ts-proto behavior Foo.toJSON({}); // => { } Foo.toJSON({ bar: undefined }); // => { } Foo.toJSON({ bar: '' }); // => { bar: '' } - note: this is the default value, but it's not omitted Foo.toJSON({ bar: 'baz' }); // => { bar: 'baz' }
// Possible future behavior, where ts-proto would normalize message Foo.toJSON({}); // => { } Foo.toJSON({ bar: undefined }); // => { } Foo.toJSON({ bar: '' }); // => { } - note: omitting the default value, as expected Foo.toJSON({ bar: 'baz' }); // => { bar: 'baz' }
- Please open an issue if you need this behavior.
Given it appears some thought has already gone into this, would this use case be supported or is the preference to use a --ts_proto_opt=
value?