Files

28 lines
734 B
Go
Raw Permalink Normal View History

2025-09-20 09:35:50 +02:00
// Package json_util provides JSON utilities including a custom RawMessage type.
2023-02-09 22:48:06 +03:30
package json_util
import (
"errors"
)
2025-09-20 09:35:50 +02:00
// RawMessage is a custom JSON raw message type that marshals empty slices as "null".
2023-02-09 22:48:06 +03:30
type RawMessage []byte
2025-09-20 09:35:50 +02:00
// MarshalJSON customizes the JSON marshaling behavior for RawMessage.
// Empty RawMessage values are marshaled as "null" instead of "[]".
2023-02-09 22:48:06 +03:30
func (m RawMessage) MarshalJSON() ([]byte, error) {
if len(m) == 0 {
return []byte("null"), nil
}
return m, nil
}
2025-09-20 09:35:50 +02:00
// UnmarshalJSON sets *m to a copy of the JSON data.
2023-02-09 22:48:06 +03:30
func (m *RawMessage) UnmarshalJSON(data []byte) error {
if m == nil {
return errors.New("json.RawMessage: UnmarshalJSON on nil pointer")
}
*m = append((*m)[0:0], data...)
return nil
}