gunk-dev/the-valley

exactjson.go

source75d050a4e31bmain's published tip history
5.6 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.
44//
45// Decode does not read embedded structs. encoding/json reads the fields of
46// a struct embedded with no json tag name as fields of the struct that
47// embeds it, chosen by Go's rules for selecting a field, and the check
48// does not follow those rules. So Decode refuses any object read into a
49// struct that embeds a struct, or a pointer to one, with no json tag name.
50// A struct embedded under a json tag name is an ordinary field.
51func Decode(data []byte, v any) error {
52 t := reflect.TypeOf(v)
53 if t == nil || t.Kind() != reflect.Pointer {
54 return &json.InvalidUnmarshalError{Type: t}
55 }
56 dec := json.NewDecoder(bytes.NewReader(data))
57 // The check reads numbers as written, so a number the decode reads
58 // into an int64 or a json.Number is not refused for overflowing a
59 // float64.
60 dec.UseNumber()
61 if err := check(dec, t, ""); err != nil {
62 return err
63 }
64 if _, err := dec.Token(); err != io.EOF {
65 return errors.New("the document holds more than one JSON value")
66 }
67 dec = json.NewDecoder(bytes.NewReader(data))
68 dec.DisallowUnknownFields()
69 return dec.Decode(v)
70}
71
72// check reads one value from dec, found at path ("" for the document),
73// and holds every object in it to t, the type the value is decoded into.
74func check(dec *json.Decoder, t reflect.Type, path string) error {
75 for t.Kind() == reflect.Pointer {
76 t = t.Elem()
77 }
78 tok, err := dec.Token()
79 if err != nil {
80 return err
81 }
82 switch tok {
83 case json.Delim('['):
84 elem := t
85 if t.Kind() == reflect.Slice || t.Kind() == reflect.Array {
86 elem = t.Elem()
87 }
88 for i := 0; dec.More(); i++ {
89 if err := check(dec, elem, fmt.Sprintf("%s[%d]", path, i)); err != nil {
90 return err
91 }
92 }
93 case json.Delim('{'):
94 var fields map[string]reflect.Type
95 if t.Kind() == reflect.Struct {
96 if fields, err = tagged(t); err != nil {
97 return fmt.Errorf("%s is read into %w", where(path), err)
98 }
99 }
100 seen := map[string]bool{}
101 for dec.More() {
102 tok, err := dec.Token()
103 if err != nil {
104 return err
105 }
106 key := tok.(string)
107 if seen[key] {
108 return fmt.Errorf("%s holds the key %q twice", where(path), key)
109 }
110 seen[key] = true
111 elem, at := t, fmt.Sprintf("%s[%q]", path, key)
112 switch t.Kind() {
113 case reflect.Struct:
114 var ok bool
115 if elem, ok = fields[key]; !ok {
116 return unknown(path, key, fields)
117 }
118 at = strings.TrimPrefix(path+"."+key, ".")
119 case reflect.Map:
120 elem = t.Elem()
121 }
122 if err := check(dec, elem, at); err != nil {
123 return err
124 }
125 }
126 default:
127 return nil
128 }
129 // The closing delimiter.
130 _, err = dec.Token()
131 return err
132}
133
134// tagged maps the name each json tag of struct type t gives to the type
135// of its field. Its error is for a t that embeds a struct with no json tag
136// name, which Decode does not read.
137func tagged(t reflect.Type) (map[string]reflect.Type, error) {
138 fields := map[string]reflect.Type{}
139 for i := range t.NumField() {
140 f := t.Field(i)
141 name, _, _ := strings.Cut(f.Tag.Get("json"), ",")
142 embedded := f.Type
143 if embedded.Kind() == reflect.Pointer {
144 embedded = embedded.Elem()
145 }
146 if f.Anonymous && name == "" && embedded.Kind() == reflect.Struct {
147 return nil, fmt.Errorf("%s, which embeds %s, and exactjson reads no embedded struct", t, f.Type)
148 }
149 if name != "" && name != "-" {
150 fields[name] = f.Type
151 }
152 }
153 return fields, nil
154}
155
156// unknown is the error for a key no field of the struct at path names.
157// When the key is a field's name spelled another way, as encoding/json
158// would have matched it, the error names that field too.
159func unknown(path, key string, fields map[string]reflect.Type) error {
160 for name := range fields {
161 if strings.EqualFold(name, key) {
162 return fmt.Errorf("%s holds the key %q, which is its field %q spelled another way", where(path), key, name)
163 }
164 }
165 return fmt.Errorf("%s holds the key %q, which is none of its fields", where(path), key)
166}
167
168// where names path in a message.
169func where(path string) string {
170 if path == "" {
171 return "the document"
172 }
173 return path
174}