@@ -5,6 +5,7 @@ package minsev // import "go.opentelemetry.io/contrib/processors/minsev"
55
66import (
77 "encoding"
8+ "encoding/json"
89 "errors"
910 "fmt"
1011 "strconv"
@@ -23,6 +24,10 @@ type Severity int
2324var (
2425 // Ensure Severity implements fmt.Stringer.
2526 _ fmt.Stringer = Severity (0 )
27+ // Ensure Severity implements json.Marshaler.
28+ _ json.Marshaler = Severity (0 )
29+ // Ensure Severity implements json.Unmarshaler.
30+ _ json.Unmarshaler = (* Severity )(nil )
2631 // Ensure Severity implements encoding.TextMarshaler.
2732 _ encoding.TextMarshaler = Severity (0 )
2833 // Ensure Severity implements encoding.TextUnmarshaler.
@@ -161,6 +166,26 @@ func (s Severity) String() string {
161166 }
162167}
163168
169+ // MarshalJSON implements [encoding/json.Marshaler] by quoting the output of
170+ // [Severity.String].
171+ func (s Severity ) MarshalJSON () ([]byte , error ) {
172+ // AppendQuote is sufficient for JSON-encoding all Severity strings. They
173+ // don't contain any runes that would produce invalid JSON when escaped.
174+ return strconv .AppendQuote (nil , s .String ()), nil
175+ }
176+
177+ // UnmarshalJSON implements [encoding/json.Unmarshaler] It accepts any string
178+ // produced by [Severity.MarshalJSON], ignoring case. It also accepts numeric
179+ // offsets that would result in a different string on output. For example,
180+ // "ERROR-8" will unmarshal as SeverityInfo.
181+ func (s * Severity ) UnmarshalJSON (data []byte ) error {
182+ str , err := strconv .Unquote (string (data ))
183+ if err != nil {
184+ return err
185+ }
186+ return s .parse (str )
187+ }
188+
164189// AppendText implements [encoding.TextAppender] by calling [Severity.String].
165190func (s Severity ) AppendText (b []byte ) ([]byte , error ) {
166191 return append (b , s .String ()... ), nil
0 commit comments