| 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. |
| 18 | package exactjson |
| 19 | |
| 20 | import ( |
| 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. |
| 51 | func 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 | // Tokens is a stream of JSON tokens, as a *json.Decoder reads them. |
| 73 | type Tokens interface { |
| 74 | Token() (json.Token, error) |
| 75 | More() bool |
| 76 | } |
| 77 | |
| 78 | // Check reads one JSON value from tokens, and holds every object in it to |
| 79 | // t, the type the value is decoded into, by the rules Decode holds a |
| 80 | // document to: a key of an object read into a struct is the name a json |
| 81 | // tag of that struct gives, spelled exactly, and no key appears twice in |
| 82 | // one object. It reads nothing after the value. |
| 83 | // |
| 84 | // Check is for a caller that decodes with a token reader of its own, such |
| 85 | // as one that stops when a context is cancelled. Such a caller checks the |
| 86 | // value with Check first, and decodes it only when Check passes it. A |
| 87 | // token reader that reads numbers as json.Number keeps a number that |
| 88 | // overflows a float64 from failing the check. |
| 89 | func Check(tokens Tokens, t reflect.Type) error { return check(tokens, t, "") } |
| 90 | |
| 91 | // check reads one value from dec, found at path ("" for the document), |
| 92 | // and holds every object in it to t, the type the value is decoded into. |
| 93 | func check(dec Tokens, t reflect.Type, path string) error { |
| 94 | for t.Kind() == reflect.Pointer { |
| 95 | t = t.Elem() |
| 96 | } |
| 97 | tok, err := dec.Token() |
| 98 | if err != nil { |
| 99 | return err |
| 100 | } |
| 101 | switch tok { |
| 102 | case json.Delim('['): |
| 103 | elem := t |
| 104 | if t.Kind() == reflect.Slice || t.Kind() == reflect.Array { |
| 105 | elem = t.Elem() |
| 106 | } |
| 107 | for i := 0; dec.More(); i++ { |
| 108 | if err := check(dec, elem, fmt.Sprintf("%s[%d]", path, i)); err != nil { |
| 109 | return err |
| 110 | } |
| 111 | } |
| 112 | case json.Delim('{'): |
| 113 | var fields map[string]reflect.Type |
| 114 | if t.Kind() == reflect.Struct { |
| 115 | if fields, err = tagged(t); err != nil { |
| 116 | return fmt.Errorf("%s is read into %w", where(path), err) |
| 117 | } |
| 118 | } |
| 119 | seen := map[string]bool{} |
| 120 | for dec.More() { |
| 121 | tok, err := dec.Token() |
| 122 | if err != nil { |
| 123 | return err |
| 124 | } |
| 125 | key := tok.(string) |
| 126 | if seen[key] { |
| 127 | return fmt.Errorf("%s holds the key %q twice", where(path), key) |
| 128 | } |
| 129 | seen[key] = true |
| 130 | elem, at := t, fmt.Sprintf("%s[%q]", path, key) |
| 131 | switch t.Kind() { |
| 132 | case reflect.Struct: |
| 133 | var ok bool |
| 134 | if elem, ok = fields[key]; !ok { |
| 135 | return unknown(path, key, fields) |
| 136 | } |
| 137 | at = strings.TrimPrefix(path+"."+key, ".") |
| 138 | case reflect.Map: |
| 139 | elem = t.Elem() |
| 140 | } |
| 141 | if err := check(dec, elem, at); err != nil { |
| 142 | return err |
| 143 | } |
| 144 | } |
| 145 | default: |
| 146 | return nil |
| 147 | } |
| 148 | // The closing delimiter. |
| 149 | _, err = dec.Token() |
| 150 | return err |
| 151 | } |
| 152 | |
| 153 | // tagged maps the name each json tag of struct type t gives to the type |
| 154 | // of its field. Its error is for a t that embeds a struct with no json tag |
| 155 | // name, which Decode does not read. |
| 156 | func tagged(t reflect.Type) (map[string]reflect.Type, error) { |
| 157 | fields := map[string]reflect.Type{} |
| 158 | for i := range t.NumField() { |
| 159 | f := t.Field(i) |
| 160 | name, _, _ := strings.Cut(f.Tag.Get("json"), ",") |
| 161 | embedded := f.Type |
| 162 | if embedded.Kind() == reflect.Pointer { |
| 163 | embedded = embedded.Elem() |
| 164 | } |
| 165 | if f.Anonymous && name == "" && embedded.Kind() == reflect.Struct { |
| 166 | return nil, fmt.Errorf("%s, which embeds %s, and exactjson reads no embedded struct", t, f.Type) |
| 167 | } |
| 168 | if name != "" && name != "-" { |
| 169 | fields[name] = f.Type |
| 170 | } |
| 171 | } |
| 172 | return fields, nil |
| 173 | } |
| 174 | |
| 175 | // unknown is the error for a key no field of the struct at path names. |
| 176 | // When the key is a field's name spelled another way, as encoding/json |
| 177 | // would have matched it, the error names that field too. |
| 178 | func unknown(path, key string, fields map[string]reflect.Type) error { |
| 179 | for name := range fields { |
| 180 | if strings.EqualFold(name, key) { |
| 181 | return fmt.Errorf("%s holds the key %q, which is its field %q spelled another way", where(path), key, name) |
| 182 | } |
| 183 | } |
| 184 | return fmt.Errorf("%s holds the key %q, which is none of its fields", where(path), key) |
| 185 | } |
| 186 | |
| 187 | // where names path in a message. |
| 188 | func where(path string) string { |
| 189 | if path == "" { |
| 190 | return "the document" |
| 191 | } |
| 192 | return path |
| 193 | } |