// Package jsonfields finds the JSON object members of a Go struct by the rules of encoding/json/v2: the fields // which a value of the struct is marshaled to and unmarshaled from, with the options of their `json` tags. // // A Go struct is a list of fields found by a breadth-first search over its fields and the fields of the structs // embedded in it. A field hides the fields of the same name deeper than it, and of two fields at the same depth // the one whose name is given by its tag. An error in the definition of the struct is reported when a value of it // is marshaled or unmarshaled, not when the type is seen: an empty map of it is still {}.
package jsonfields import ( ) // The types which the json packages give this package: the ones it can't import. var ( // RawValueType is jsontext.Value, which is an embedded fallback. RawValueType reflect.Type // MethodTypes are the interfaces of the methods of marshaling and unmarshaling: a type which has one of them // can't be embedded. MethodTypes []reflect.Type ) var isZeroerType = reflect.TypeFor[interface{ IsZero() bool }]() // Casing is how the name of a field is matched when unmarshaling, by its `case` option. type Casing int8 const ( CaseIgnore Casing = 1 << iota // case:ignore, which ignores the case, '-' and '_' CaseStrict // case:strict ) // Options are the options of the `json` tag of a field. type Options struct { Name string // the JSON object name QuotedName string // Name as a JSON string HasName bool // whether the tag gives the name Casing Casing Embed bool OmitZero bool OmitEmpty bool String bool Format string } // Field is a JSON object member of a struct. type Field struct { Options // Index is the index of the field by reflect.Type.FieldByIndex: the fields of the embedded structs on the // way to it, and the field. Index []int Type reflect.Type // ID is the place of the field in the breadth-first order of the fields. ID int // HasIsZero is whether the type of the field, or the pointer to it, has the IsZero method, which decides // whether the field is omitted by omitzero. HasIsZero bool } // Fields are the JSON object members of a struct. type Fields struct { // List is the fields in the depth-first order of their indexes, which is the order they are marshaled in. List []Field // Fallback is the embedded field of a map or of jsontext.Value which holds the members of no other field, or // nil. Fallback *Field // Err is the first error of the definition of the struct, or nil. Err *Error // FormatErr is the error of the first field with the `format` option, which encoding/json/v2 doesn't // support, or nil. FormatErr *Error } // Error is an error of the definition of a struct type. type Error struct { GoType reflect.Type Err error } var errNoExportedFields = errors.New("Go struct has no exported fields") //nolint:staticcheck // the text of encoding/json/v2 // Of returns the JSON object members of the struct type t. func ( reflect.Type) *Fields { := &builder{fs: &Fields{}, queue: []visit{{, nil, true}}, seen: map[reflect.Type]bool{: true}} for len(.queue) > 0 { := .queue[0] .queue = .queue[1:] .visitStruct() } .fs.List = dominantFields(.all) if := len(.fallbacks); == 1 || ( > 1 && len(.fallbacks[0].Index) != len(.fallbacks[1].Index)) { .fs.Fallback = &.fallbacks[0] } return .fs } // builder finds the fields of a struct by a breadth-first search over the structs embedded in it ( see Of ). type builder struct { fs *Fields queue []visit seen map[reflect.Type]bool // all are the members of every struct visited, and fallbacks the embedded fallbacks, of which the ones which // hide the others are chosen. all, fallbacks []Field } // visit is a struct of the search, at the index of the struct which embeds it. type visit struct { typ reflect.Type index []int children bool // whether the structs embedded in it are visited } // structVisit is the state of a struct being visited. type structVisit struct { visit names map[string]int // the members of the struct by their names: the index of their field fallback int // the index of the embedded fallback of the struct, or -1 } func ( *builder) ( reflect.Type, string, ...any) { if .fs.Err == nil { .fs.Err = &Error{GoType: , Err: fmt.Errorf(, ...)} } } // visitStruct adds the members of the fields of the struct v, and queues the structs it embeds. func ( *builder) ( visit) { := &structVisit{visit: , names: map[string]int{}, fallback: -1} var , bool for := range .typ.NumField() { := .typ.Field() , := .Tag.Lookup("json") = || , , := parseOptions() if != nil && .fs.Err == nil { .fs.Err = &Error{GoType: .typ, Err: } } if { continue } = true := Field{Options: , Index: append(slices.Clip(.index), ), Type: .Type} if .Anonymous && !.HasName { if indirect(.Type).Kind() == reflect.Struct { .Embed = true // an embedded struct is embedded in the JSON object unless it is named } else { .failf(.typ, "embedded Go struct field %s of non-struct type must be explicitly given a JSON name", .Name) } } if .Embed { .addEmbedded(, , ) } else { .addMember(, , ) } } // a struct which has fields but no member is most likely a mistake ( a struct of unexported fields, as an // error of errors.New is ), unless a field has a tag, which tells that it is meant to be so. if .typ.NumField() > 0 && ! && ! && .fs.Err == nil { .fs.Err = &Error{GoType: .typ, Err: errNoExportedFields} } } // addMember adds the field f, a member of its own, of the struct s. func ( *builder) ( *structVisit, reflect.StructField, Field) { := .typ if !.IsExported() { // only an embedded struct of an unexported type may have exported fields. := indirect(.Type) if !.Anonymous || .Kind() != reflect.Struct { .failf(, "Go struct field %s is not exported", .Name) return } if implementsAny(, MethodTypes) || (.OmitZero && implementsAny(, []reflect.Type{isZeroerType})) { .failf(, "Go struct field %s is not exported for method calls", .Name) return } } .HasIsZero = .Type.Implements(isZeroerType) || reflect.PointerTo(.Type).Implements(isZeroerType) if , := .names[.Name]; { // the field is still listed: a field which hides both of them is chosen after. .failf(, "Go struct fields %s and %s conflict over JSON object name %q", .Field().Name, .Name, .Name) } .names[.Name] = .Index[len(.Index)-1] .ID = len(.all) .all = append(.all, ) if .Format != "" && .fs.FormatErr == nil { .fs.FormatErr = &Error{GoType: , Err: fmt.Errorf("Go struct field %s has unsupported `format` tag option", .Name)} //nolint:staticcheck // the text of encoding/json/v2 } } // addEmbedded adds the field f, whose members are members of the object of the struct s: a struct, whose fields // are visited later, or an embedded fallback. func ( *builder) ( *structVisit, reflect.StructField, Field) { := .typ if .Options != (Options{Name: .Name, QuotedName: .QuotedName, Embed: true}) { .failf(, "Go struct field %s cannot have any options other than `embed` specified", .Name) if .HasName { .addMember(, , ) return } .Options = Options{Name: .Name, QuotedName: .QuotedName, Embed: true} } := indirect(.Type) if != RawValueType && implementsAny(, MethodTypes) { .failf(, "embedded Go struct field %s of type %s must not implement marshal or unmarshal methods", .Name, ) } if .Kind() == reflect.Struct { if .children { .queue = append(.queue, visit{, .Index, !.seen[]}) } .seen[] = true return } if !.IsExported() { .failf(, "embedded Go struct field %s is not exported", .Name) return } switch { case == RawValueType: case .Kind() == reflect.Map && .Key().Kind() == reflect.String: if implementsAny(.Key(), MethodTypes) { .failf(, "embedded map field %s of type %s must have a string key that does not implement marshal or unmarshal methods", .Name, ) .addMember(, , ) return } default: .failf(, "embedded Go struct field %s of type %s must be a Go struct, Go map of string key, or jsontext.Value", .Name, ) .addMember(, , ) return } if .fallback >= 0 { // it is still listed: one deeper than the other is chosen after. .failf(, "embedded Go struct fields %s and %s cannot both be a Go map or jsontext.Value", .Field(.fallback).Name, .Name) } .fallback = .Index[len(.Index)-1] .fallbacks = append(.fallbacks, ) } // dominantFields returns the members of the object of the fields all: of the fields of a name, the one at the // shallowest depth, or the one of them with the name in its tag if the others have none, and otherwise none. They // are numbered in their breadth-first order, and listed in their depth-first order. func dominantFields( []Field) []Field { slices.SortStableFunc(, func(, Field) int { return cmp.Or(strings.Compare(.Name, .Name), cmp.Compare(len(.Index), len(.Index)), compareBool(!.HasName, !.HasName)) }) var []Field for len() > 0 { := 1 for < len() && [].Name == [0].Name { ++ } if == 1 || len([0].Index) != len([1].Index) || [0].HasName != [1].HasName { = append(, [0]) } = [:] } slices.SortFunc(, func(, Field) int { return cmp.Compare(.ID, .ID) }) for := range { [].ID = } slices.SortFunc(, func(, Field) int { return slices.Compare(.Index, .Index) }) return } // indirect returns the type a field of type t embeds: the element of an unnamed pointer, or t. func indirect( reflect.Type) reflect.Type { if .Kind() == reflect.Pointer && .Name() == "" { return .Elem() } return } func implementsAny( reflect.Type, []reflect.Type) bool { for , := range { if .Implements() || reflect.PointerTo().Implements() { return true } } return false } // compareBool orders false before true. func compareBool(, bool) int { switch { case ! && : return -1 case && !: return +1 } return 0 } // parseOptions parses the `json` tag of the field. A field is ignored by the tag "-", and an unexported field // which is not embedded is ignored, whose tag is an error unless it is "-". func parseOptions( reflect.StructField) (Options, bool, error) { var Options var error , := .Tag.Lookup("json") if == "-" { return Options{}, true, nil } := func( string, ...any) { if == nil { = fmt.Errorf(, ...) } } if !.IsExported() && !.Anonymous { if { ("unexported Go struct field %s cannot have non-ignored `json:%q` tag", .Name, ) } return Options{}, true, } .Name = .Name if != "" && [0] != ',' { // almost any text is a name, up to the comma: a backslash and the quotes are reserved. := strings.IndexAny(, ",\\'\"`") if < 0 { = len() } := [:] var error if < len() && [] != ',' { , , = consumeOption(, false) if != nil { ("Go struct field %s has malformed `json` tag: %v", .Name, ) } } if !utf8.ValidString() { ("Go struct field %s has JSON object name %q with invalid UTF-8", .Name, ) = string([]rune()) } if == nil { .HasName = true .Name = } = [:] } .QuotedName = quoteName(.Name) var bool := map[string]bool{} for != "" { if [0] != ',' { ("Go struct field %s has malformed `json` tag: invalid character %q before next option (expecting ',')", .Name, [0]) } else { = [1:] if == "" { ("Go struct field %s has malformed `json` tag: invalid trailing ',' character", .Name) break } } , , := consumeOption(, false) if != nil { ("Go struct field %s has malformed `json` tag: %v", .Name, ) } := [:] = [:] switch { case : ("Go struct field %s has `format` tag option that was not specified last", .Name) case strings.HasPrefix(, "'") && strings.TrimFunc(, isLetterOrDigit) == "": ("Go struct field %s has unnecessarily quoted appearance of `%s` tag option; specify `%s` instead", .Name, , ) } switch { case "case": if !strings.HasPrefix(, ":") { ("Go struct field %s is missing value for `case` tag option; specify `case:ignore` or `case:strict` instead", .Name) break } = [1:] , , := consumeOption(, false) if != nil { ("Go struct field %s has malformed value for `case` tag option: %v", .Name, ) break } := [:] = [:] if strings.HasPrefix(, "'") { ("Go struct field %s has unnecessarily quoted appearance of `case:%s` tag option; specify `case:%s` instead", .Name, , ) } switch { case "ignore": .Casing |= CaseIgnore case "strict": .Casing |= CaseStrict default: ("Go struct field %s has unknown `case:%s` tag value", .Name, ) } case "embed": .Embed = true case "omitzero": .OmitZero = true case "omitempty": .OmitEmpty = true case "string": .String = true case "format": if !strings.HasPrefix(, ":") { ("Go struct field %s is missing value for `format` tag option", .Name) break } = [1:] , , := consumeOption(, true) if != nil { ("Go struct field %s has malformed value for `format` tag option: %v", .Name, ) break } if == "" { ("Go struct field %s cannot have empty value for `format` tag option", .Name) break } = [:] .Format = = true default: // an option which looks like one of them by its letters is a mistake for it. switch := strings.ReplaceAll(strings.ToLower(), "_", ""); { case "case", "embed", "omitzero", "omitempty", "string", "format": ("Go struct field %s has invalid appearance of `%s` tag option; specify `%s` instead", .Name, , ) } // the other options are ignored, as a future version may know them. } switch { case .Casing == CaseIgnore|CaseStrict: ("Go struct field %s cannot have both `case:ignore` and `case:strict` tag options", .Name) case []: ("Go struct field %s has duplicate appearance of `%s` tag option", .Name, ) } [] = true } return , false, } // consumeOption returns the option at the start of in, a Go identifier or, if quoted is true, a single-quoted // string, and its length in in. An invalid option is the text up to the next comma, with an error. func consumeOption( string, bool) (string, int, error) { := strings.IndexByte(, ',') if < 0 { = len() } , := utf8.DecodeRuneInString() switch { case == '_' || unicode.IsLetter(): := len() - len(strings.TrimLeftFunc(, isLetterOrDigit)) return [:], , nil case == "": return , 0, fmt.Errorf("unexpected EOF") case == '\'' && : // a Go string literal in single quotes, which a struct tag can have where it can't have double quotes. := []byte{'"'} := false for := 1; < len(); { , := utf8.DecodeRuneInString([:]) switch { case : if == '\'' { = [:len()-1] // \' is ' } = false case == '\\': = true case == '"': = append(, '\\') case == '\'': ++ , := strconv.Unquote(string(append(, '"'))) if != nil { return [:], , fmt.Errorf("invalid single-quoted string: %s", [:]) } return , , nil } = append(, [:+]...) += } return [:], , fmt.Errorf("single-quoted string not terminated: %s...", [:min(len(), 10)]) //nolint:staticcheck // the text of encoding/json/v2 case : return [:], , fmt.Errorf("invalid character %q at start of option (expecting Unicode letter or single quote)", ) default: return [:], , fmt.Errorf("invalid character %q at start of option (expecting Unicode letter)", ) } } // quoteName returns the name as a JSON string, escaped as jsontext escapes a string by default. func quoteName( string) string { , := jsonstring.AppendQuoted(jsonstring.TextEscaper(false, false), nil, ) return string() } func isLetterOrDigit( rune) bool { return == '_' || unicode.IsLetter() || unicode.IsNumber() } // FoldName returns the name of which the names that case:ignore matches are the same: the case is folded, and '_' // and '-' are removed. func ( []byte) []byte { := make([]byte, 0, len()) for := 0; < len(); { if := []; < utf8.RuneSelf { if != '_' && != '-' { if 'a' <= && <= 'z' { -= 'a' - 'A' } = append(, ) } ++ continue } , := utf8.DecodeRune([:]) = utf8.AppendRune(, foldRune()) += } return } // foldRune returns the smallest rune of the runes which r folds to: the same one for all of them. func foldRune( rune) rune { := for := unicode.SimpleFold(); != ; = unicode.SimpleFold() { = min(, ) } return }