gunk-dev/the-valley

exactjson.go

source6db7e2f30e24main's published tip history
4.7 KiB
1// Package exactjson decodes one JSON document into a Go value, and first
2// refuses any key that the value's type does not name exactly.
3//
4// encoding/json matches an object key to a struct field without regard to
5// case, and DisallowUnknownFields does not change that. cue keeps keys that
6// differ only in case apart, and so does Nix. A CUE document may reopen a
7// definition of the schema it is checked against, and add a field to it.
8// So a document can carry Grants beside an empty grants, and encoding/json
9// reads the first into the second: a reviewer reading the canonical field
10// sees nothing, and the program reads a grant.
11//
12// A key that appears twice in one object is the same problem in another
13// form. encoding/json keeps the last of two values, and merges two objects
14// read into one map or struct, so a reader of the first sees less than the
15// program reads.
16//
17// The package depends on the standard library alone.
18package exactjson
19
20import (
21 "bytes"
22 "encoding/json"
23 "errors"
24 "fmt"
25 "io"
26 "reflect"
27 "strings"
28)
29
30// Decode decodes data into v, which must be a non-nil pointer. Before it
31// decodes anything, it reads every object in data, at every depth, and
32// refuses:
33//
34// - a key of an object read into a struct that is not the name a json
35// tag of that struct gives, spelled exactly;
36// - a key that appears twice in one object;
37// - anything after the first JSON value.
38//
39// A struct field takes a key only through the name its json tag gives, so
40// a field with no tag name takes none. The keys of an object read into a
41// map, an interface or a json.RawMessage are data, and any key passes: a
42// map's values are held to its element type, and the rest are checked for
43// repeated keys alone.
44func Decode(data []byte, v any) error {
45 t := reflect.TypeOf(v)
46 if t == nil || t.Kind() != reflect.Pointer {
47 return &json.InvalidUnmarshalError{Type: t}
48 }
49 dec := json.NewDecoder(bytes.NewReader(data))
50 // The check reads numbers as written, so a number the decode reads
51 // into an int64 or a json.Number is not refused for overflowing a
52 // float64.
53 dec.UseNumber()
54 if err := check(dec, t, ""); err != nil {
55 return err
56 }
57 if _, err := dec.Token(); err != io.EOF {
58 return errors.New("the document holds more than one JSON value")
59 }
60 dec = json.NewDecoder(bytes.NewReader(data))
61 dec.DisallowUnknownFields()
62 return dec.Decode(v)
63}
64
65// check reads one value from dec, found at path ("" for the document),
66// and holds every object in it to t, the type the value is decoded into.
67func check(dec *json.Decoder, t reflect.Type, path string) error {
68 for t.Kind() == reflect.Pointer {
69 t = t.Elem()
70 }
71 tok, err := dec.Token()
72 if err != nil {
73 return err
74 }
75 switch tok {
76 case json.Delim('['):
77 elem := t
78 if t.Kind() == reflect.Slice || t.Kind() == reflect.Array {
79 elem = t.Elem()
80 }
81 for i := 0; dec.More(); i++ {
82 if err := check(dec, elem, fmt.Sprintf("%s[%d]", path, i)); err != nil {
83 return err
84 }
85 }
86 case json.Delim('{'):
87 var fields map[string]reflect.Type
88 if t.Kind() == reflect.Struct {
89 fields = tagged(t)
90 }
91 seen := map[string]bool{}
92 for dec.More() {
93 tok, err := dec.Token()
94 if err != nil {
95 return err
96 }
97 key := tok.(string)
98 if seen[key] {
99 return fmt.Errorf("%s holds the key %q twice", where(path), key)
100 }
101 seen[key] = true
102 elem, at := t, fmt.Sprintf("%s[%q]", path, key)
103 switch t.Kind() {
104 case reflect.Struct:
105 var ok bool
106 if elem, ok = fields[key]; !ok {
107 return unknown(path, key, fields)
108 }
109 at = strings.TrimPrefix(path+"."+key, ".")
110 case reflect.Map:
111 elem = t.Elem()
112 }
113 if err := check(dec, elem, at); err != nil {
114 return err
115 }
116 }
117 default:
118 return nil
119 }
120 // The closing delimiter.
121 _, err = dec.Token()
122 return err
123}
124
125// tagged maps the name each json tag of struct type t gives to the type
126// of its field.
127func tagged(t reflect.Type) map[string]reflect.Type {
128 fields := map[string]reflect.Type{}
129 for i := range t.NumField() {
130 f := t.Field(i)
131 if name, _, _ := strings.Cut(f.Tag.Get("json"), ","); name != "" && name != "-" {
132 fields[name] = f.Type
133 }
134 }
135 return fields
136}
137
138// unknown is the error for a key no field of the struct at path names.
139// When the key is a field's name spelled another way, as encoding/json
140// would have matched it, the error names that field too.
141func unknown(path, key string, fields map[string]reflect.Type) error {
142 for name := range fields {
143 if strings.EqualFold(name, key) {
144 return fmt.Errorf("%s holds the key %q, which is its field %q spelled another way", where(path), key, name)
145 }
146 }
147 return fmt.Errorf("%s holds the key %q, which is none of its fields", where(path), key)
148}
149
150// where names path in a message.
151func where(path string) string {
152 if path == "" {
153 return "the document"
154 }
155 return path
156}