-
Notifications
You must be signed in to change notification settings - Fork 0
/
array.go
38 lines (34 loc) · 850 Bytes
/
array.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package ojson
import (
"bytes"
"encoding/json"
"fmt"
)
// Array represents a slice of any values. When using it to decode a
// JSON array it ensures that embedded JSON objects are decoded as
// [Object].
type Array []any
// MarshalJSON implements the [json.Marshaler] interface.
func (a *Array) UnmarshalJSON(d []byte) error {
dec := json.NewDecoder(bytes.NewReader(d))
tok, err := dec.Token()
if err != nil {
return err
}
if delim, ok := tok.(json.Delim); ok && delim == '[' {
return a.unmarshalJSON(dec)
}
return fmt.Errorf(`expected "[", got %q`, tok)
}
// UnmarshalJSON implements the [json.Unmarshaler] interface.
func (a *Array) unmarshalJSON(d *json.Decoder) error {
for d.More() {
var v Any
if err := v.unmarshalJSON(d); err != nil {
return err
}
*a = append(*a, v.Value())
}
_, err := d.Token()
return err
}