fs: fix tristate conversion to JSON

This commit is contained in:
Nick Craig-Wood 2023-03-16 18:20:23 +00:00
parent bad8a01850
commit 5f4d7154c0
2 changed files with 23 additions and 0 deletions

View File

@ -70,3 +70,11 @@ func (t *Tristate) UnmarshalJSON(in []byte) error {
}
return nil
}
// MarshalJSON encodes it as a bool or nil for unset
func (t *Tristate) MarshalJSON() ([]byte, error) {
if !t.Valid {
return json.Marshal(nil)
}
return json.Marshal(t.Value)
}

View File

@ -85,3 +85,18 @@ func TestTristateUnmarshalJSON(t *testing.T) {
assert.Equal(t, test.want, got, test.in)
}
}
func TestTristateMarshalJSON(t *testing.T) {
for _, test := range []struct {
in Tristate
want string
}{
{Tristate{}, `null`},
{Tristate{Valid: true, Value: true}, `true`},
{Tristate{Valid: true, Value: false}, `false`},
} {
got, err := json.Marshal(&test.in)
require.NoError(t, err)
assert.Equal(t, test.want, string(got), fmt.Sprintf("%#v", test.in))
}
}