1 // Copyright 2010 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
5 // Package json implements encoding and decoding of JSON objects as defined in
6 // RFC 4627. The mapping between JSON objects and Go values is described
7 // in the documentation for the Marshal and Unmarshal functions.
9 // See "JSON and Go" for an introduction to this package:
10 // http://golang.org/doc/articles/json_and_go.html
28 // Marshal returns the JSON encoding of v.
30 // Marshal traverses the value v recursively.
31 // If an encountered value implements the Marshaler interface
32 // and is not a nil pointer, Marshal calls its MarshalJSON method
33 // to produce JSON. The nil pointer exception is not strictly necessary
34 // but mimics a similar, necessary exception in the behavior of
37 // Otherwise, Marshal uses the following type-dependent default encodings:
39 // Boolean values encode as JSON booleans.
41 // Floating point, integer, and Number values encode as JSON numbers.
43 // String values encode as JSON strings. InvalidUTF8Error will be returned
44 // if an invalid UTF-8 sequence is encountered.
45 // The angle brackets "<" and ">" are escaped to "\u003c" and "\u003e"
46 // to keep some browsers from misinterpreting JSON output as HTML.
48 // Array and slice values encode as JSON arrays, except that
49 // []byte encodes as a base64-encoded string, and a nil slice
50 // encodes as the null JSON object.
52 // Struct values encode as JSON objects. Each exported struct field
53 // becomes a member of the object unless
54 // - the field's tag is "-", or
55 // - the field is empty and its tag specifies the "omitempty" option.
56 // The empty values are false, 0, any
57 // nil pointer or interface value, and any array, slice, map, or string of
58 // length zero. The object's default key string is the struct field name
59 // but can be specified in the struct field's tag value. The "json" key in
60 // the struct field's tag value is the key name, followed by an optional comma
61 // and options. Examples:
63 // // Field is ignored by this package.
64 // Field int `json:"-"`
66 // // Field appears in JSON as key "myName".
67 // Field int `json:"myName"`
69 // // Field appears in JSON as key "myName" and
70 // // the field is omitted from the object if its value is empty,
71 // // as defined above.
72 // Field int `json:"myName,omitempty"`
74 // // Field appears in JSON as key "Field" (the default), but
75 // // the field is skipped if empty.
76 // // Note the leading comma.
77 // Field int `json:",omitempty"`
79 // The "string" option signals that a field is stored as JSON inside a
80 // JSON-encoded string. It applies only to fields of string, floating point,
81 // or integer types. This extra level of encoding is sometimes used when
82 // communicating with JavaScript programs:
84 // Int64String int64 `json:",string"`
86 // The key name will be used if it's a non-empty string consisting of
87 // only Unicode letters, digits, dollar signs, percent signs, hyphens,
88 // underscores and slashes.
90 // Anonymous struct fields are usually marshaled as if their inner exported fields
91 // were fields in the outer struct, subject to the usual Go visibility rules amended
92 // as described in the next paragraph.
93 // An anonymous struct field with a name given in its JSON tag is treated as
94 // having that name, rather than being anonymous.
96 // The Go visibility rules for struct fields are amended for JSON when
97 // deciding which field to marshal or unmarshal. If there are
98 // multiple fields at the same level, and that level is the least
99 // nested (and would therefore be the nesting level selected by the
100 // usual Go rules), the following extra rules apply:
102 // 1) Of those fields, if any are JSON-tagged, only tagged fields are considered,
103 // even if there are multiple untagged fields that would otherwise conflict.
104 // 2) If there is exactly one field (tagged or not according to the first rule), that is selected.
105 // 3) Otherwise there are multiple fields, and all are ignored; no error occurs.
107 // Handling of anonymous struct fields is new in Go 1.1.
108 // Prior to Go 1.1, anonymous struct fields were ignored. To force ignoring of
109 // an anonymous struct field in both current and earlier versions, give the field
110 // a JSON tag of "-".
112 // Map values encode as JSON objects.
113 // The map's key type must be string; the object keys are used directly
116 // Pointer values encode as the value pointed to.
117 // A nil pointer encodes as the null JSON object.
119 // Interface values encode as the value contained in the interface.
120 // A nil interface value encodes as the null JSON object.
122 // Channel, complex, and function values cannot be encoded in JSON.
123 // Attempting to encode such a value causes Marshal to return
124 // an UnsupportedTypeError.
126 // JSON cannot represent cyclic data structures and Marshal does not
127 // handle them. Passing cyclic structures to Marshal will result in
128 // an infinite recursion.
130 func Marshal(v
interface{}) ([]byte, error
) {
136 return e
.Bytes(), nil
139 // MarshalIndent is like Marshal but applies Indent to format the output.
140 func MarshalIndent(v
interface{}, prefix
, indent
string) ([]byte, error
) {
146 err
= Indent(&buf
, b
, prefix
, indent
)
150 return buf
.Bytes(), nil
153 // HTMLEscape appends to dst the JSON-encoded src with <, >, &, U+2028 and U+2029
154 // characters inside string literals changed to \u003c, \u003e, \u0026, \u2028, \u2029
155 // so that the JSON will be safe to embed inside HTML <script> tags.
156 // For historical reasons, web browsers don't honor standard HTML
157 // escaping within <script> tags, so an alternative JSON encoding must
159 func HTMLEscape(dst
*bytes
.Buffer
, src
[]byte) {
160 // The characters can only appear in string literals,
161 // so just scan the string one byte at a time.
163 for i
, c
:= range src
{
164 if c
== '<' || c
== '>' || c
== '&' {
166 dst
.Write(src
[start
:i
])
168 dst
.WriteString(`\u00`)
169 dst
.WriteByte(hex
[c
>>4])
170 dst
.WriteByte(hex
[c
&0xF])
173 // Convert U+2028 and U+2029 (E2 80 A8 and E2 80 A9).
174 if c
== 0xE2 && i
+2 < len(src
) && src
[i
+1] == 0x80 && src
[i
+2]&^1 == 0xA8 {
176 dst
.Write(src
[start
:i
])
178 dst
.WriteString(`\u202`)
179 dst
.WriteByte(hex
[src
[i
+2]&0xF])
183 if start
< len(src
) {
184 dst
.Write(src
[start
:])
188 // Marshaler is the interface implemented by objects that
189 // can marshal themselves into valid JSON.
190 type Marshaler
interface {
191 MarshalJSON() ([]byte, error
)
194 // An UnsupportedTypeError is returned by Marshal when attempting
195 // to encode an unsupported value type.
196 type UnsupportedTypeError
struct {
200 func (e
*UnsupportedTypeError
) Error() string {
201 return "json: unsupported type: " + e
.Type
.String()
204 type UnsupportedValueError
struct {
209 func (e
*UnsupportedValueError
) Error() string {
210 return "json: unsupported value: " + e
.Str
213 // Before Go 1.2, an InvalidUTF8Error was returned by Marshal when
214 // attempting to encode a string value with invalid UTF-8 sequences.
215 // As of Go 1.2, Marshal instead coerces the string to valid UTF-8 by
216 // replacing invalid bytes with the Unicode replacement rune U+FFFD.
217 // This error is no longer generated but is kept for backwards compatibility
218 // with programs that might mention it.
219 type InvalidUTF8Error
struct {
220 S
string // the whole string value that caused the error
223 func (e
*InvalidUTF8Error
) Error() string {
224 return "json: invalid UTF-8 in string: " + strconv
.Quote(e
.S
)
227 type MarshalerError
struct {
232 func (e
*MarshalerError
) Error() string {
233 return "json: error calling MarshalJSON for type " + e
.Type
.String() + ": " + e
.Err
.Error()
236 var hex
= "0123456789abcdef"
238 // An encodeState encodes JSON into a bytes.Buffer.
239 type encodeState
struct {
240 bytes
.Buffer
// accumulated output
244 var encodeStatePool sync
.Pool
246 func newEncodeState() *encodeState
{
247 if v
:= encodeStatePool
.Get(); v
!= nil {
248 e
:= v
.(*encodeState
)
252 return new(encodeState
)
255 func (e
*encodeState
) marshal(v
interface{}) (err error
) {
257 if r
:= recover(); r
!= nil {
258 if _
, ok
:= r
.(runtime
.Error
); ok
{
261 if s
, ok
:= r
.(string); ok
{
267 e
.reflectValue(reflect
.ValueOf(v
))
271 func (e
*encodeState
) error(err error
) {
275 var byteSliceType
= reflect
.TypeOf([]byte(nil))
277 func isEmptyValue(v reflect
.Value
) bool {
279 case reflect
.Array
, reflect
.Map
, reflect
.Slice
, reflect
.String
:
283 case reflect
.Int
, reflect
.Int8
, reflect
.Int16
, reflect
.Int32
, reflect
.Int64
:
285 case reflect
.Uint
, reflect
.Uint8
, reflect
.Uint16
, reflect
.Uint32
, reflect
.Uint64
, reflect
.Uintptr
:
287 case reflect
.Float32
, reflect
.Float64
:
288 return v
.Float() == 0
289 case reflect
.Interface
, reflect
.Ptr
:
295 func (e
*encodeState
) reflectValue(v reflect
.Value
) {
296 valueEncoder(v
)(e
, v
, false)
299 type encoderFunc
func(e
*encodeState
, v reflect
.Value
, quoted
bool)
301 var encoderCache
struct {
303 m
map[reflect
.Type
]encoderFunc
306 func valueEncoder(v reflect
.Value
) encoderFunc
{
308 return invalidValueEncoder
310 return typeEncoder(v
.Type())
313 func typeEncoder(t reflect
.Type
) encoderFunc
{
315 f
:= encoderCache
.m
[t
]
316 encoderCache
.RUnlock()
321 // To deal with recursive types, populate the map with an
322 // indirect func before we build it. This type waits on the
323 // real func (f) to be ready and then calls it. This indirect
324 // func is only used for recursive types.
326 if encoderCache
.m
== nil {
327 encoderCache
.m
= make(map[reflect
.Type
]encoderFunc
)
329 var wg sync
.WaitGroup
331 encoderCache
.m
[t
] = func(e
*encodeState
, v reflect
.Value
, quoted
bool) {
335 encoderCache
.Unlock()
337 // Compute fields without lock.
338 // Might duplicate effort but won't hold other computations back.
339 f
= newTypeEncoder(t
, true)
342 encoderCache
.m
[t
] = f
343 encoderCache
.Unlock()
348 marshalerType
= reflect
.TypeOf(new(Marshaler
)).Elem()
349 textMarshalerType
= reflect
.TypeOf(new(encoding
.TextMarshaler
)).Elem()
352 // newTypeEncoder constructs an encoderFunc for a type.
353 // The returned encoder only checks CanAddr when allowAddr is true.
354 func newTypeEncoder(t reflect
.Type
, allowAddr
bool) encoderFunc
{
355 if t
.Implements(marshalerType
) {
356 return marshalerEncoder
358 if t
.Kind() != reflect
.Ptr
&& allowAddr
{
359 if reflect
.PtrTo(t
).Implements(marshalerType
) {
360 return newCondAddrEncoder(addrMarshalerEncoder
, newTypeEncoder(t
, false))
364 if t
.Implements(textMarshalerType
) {
365 return textMarshalerEncoder
367 if t
.Kind() != reflect
.Ptr
&& allowAddr
{
368 if reflect
.PtrTo(t
).Implements(textMarshalerType
) {
369 return newCondAddrEncoder(addrTextMarshalerEncoder
, newTypeEncoder(t
, false))
376 case reflect
.Int
, reflect
.Int8
, reflect
.Int16
, reflect
.Int32
, reflect
.Int64
:
378 case reflect
.Uint
, reflect
.Uint8
, reflect
.Uint16
, reflect
.Uint32
, reflect
.Uint64
, reflect
.Uintptr
:
380 case reflect
.Float32
:
381 return float32Encoder
382 case reflect
.Float64
:
383 return float64Encoder
386 case reflect
.Interface
:
387 return interfaceEncoder
389 return newStructEncoder(t
)
391 return newMapEncoder(t
)
393 return newSliceEncoder(t
)
395 return newArrayEncoder(t
)
397 return newPtrEncoder(t
)
399 return unsupportedTypeEncoder
403 func invalidValueEncoder(e
*encodeState
, v reflect
.Value
, quoted
bool) {
404 e
.WriteString("null")
407 func marshalerEncoder(e
*encodeState
, v reflect
.Value
, quoted
bool) {
408 if v
.Kind() == reflect
.Ptr
&& v
.IsNil() {
409 e
.WriteString("null")
412 m
:= v
.Interface().(Marshaler
)
413 b
, err
:= m
.MarshalJSON()
415 // copy JSON into buffer, checking validity.
416 err
= compact(&e
.Buffer
, b
, true)
419 e
.error(&MarshalerError
{v
.Type(), err
})
423 func addrMarshalerEncoder(e
*encodeState
, v reflect
.Value
, quoted
bool) {
426 e
.WriteString("null")
429 m
:= va
.Interface().(Marshaler
)
430 b
, err
:= m
.MarshalJSON()
432 // copy JSON into buffer, checking validity.
433 err
= compact(&e
.Buffer
, b
, true)
436 e
.error(&MarshalerError
{v
.Type(), err
})
440 func textMarshalerEncoder(e
*encodeState
, v reflect
.Value
, quoted
bool) {
441 if v
.Kind() == reflect
.Ptr
&& v
.IsNil() {
442 e
.WriteString("null")
445 m
:= v
.Interface().(encoding
.TextMarshaler
)
446 b
, err
:= m
.MarshalText()
448 _
, err
= e
.stringBytes(b
)
451 e
.error(&MarshalerError
{v
.Type(), err
})
455 func addrTextMarshalerEncoder(e
*encodeState
, v reflect
.Value
, quoted
bool) {
458 e
.WriteString("null")
461 m
:= va
.Interface().(encoding
.TextMarshaler
)
462 b
, err
:= m
.MarshalText()
464 _
, err
= e
.stringBytes(b
)
467 e
.error(&MarshalerError
{v
.Type(), err
})
471 func boolEncoder(e
*encodeState
, v reflect
.Value
, quoted
bool) {
476 e
.WriteString("true")
478 e
.WriteString("false")
485 func intEncoder(e
*encodeState
, v reflect
.Value
, quoted
bool) {
486 b
:= strconv
.AppendInt(e
.scratch
[:0], v
.Int(), 10)
496 func uintEncoder(e
*encodeState
, v reflect
.Value
, quoted
bool) {
497 b
:= strconv
.AppendUint(e
.scratch
[:0], v
.Uint(), 10)
507 type floatEncoder
int // number of bits
509 func (bits floatEncoder
) encode(e
*encodeState
, v reflect
.Value
, quoted
bool) {
511 if math
.IsInf(f
, 0) || math
.IsNaN(f
) {
512 e
.error(&UnsupportedValueError
{v
, strconv
.FormatFloat(f
, 'g', -1, int(bits
))})
514 b
:= strconv
.AppendFloat(e
.scratch
[:0], f
, 'g', -1, int(bits
))
525 float32Encoder
= (floatEncoder(32)).encode
526 float64Encoder
= (floatEncoder(64)).encode
529 func stringEncoder(e
*encodeState
, v reflect
.Value
, quoted
bool) {
530 if v
.Type() == numberType
{
533 numStr
= "0" // Number's zero-val
535 e
.WriteString(numStr
)
539 sb
, err
:= Marshal(v
.String())
549 func interfaceEncoder(e
*encodeState
, v reflect
.Value
, quoted
bool) {
551 e
.WriteString("null")
554 e
.reflectValue(v
.Elem())
557 func unsupportedTypeEncoder(e
*encodeState
, v reflect
.Value
, quoted
bool) {
558 e
.error(&UnsupportedTypeError
{v
.Type()})
561 type structEncoder
struct {
563 fieldEncs
[]encoderFunc
566 func (se
*structEncoder
) encode(e
*encodeState
, v reflect
.Value
, quoted
bool) {
569 for i
, f
:= range se
.fields
{
570 fv
:= fieldByIndex(v
, f
.index
)
571 if !fv
.IsValid() || f
.omitEmpty
&& isEmptyValue(fv
) {
581 se
.fieldEncs
[i
](e
, fv
, f
.quoted
)
586 func newStructEncoder(t reflect
.Type
) encoderFunc
{
587 fields
:= cachedTypeFields(t
)
588 se
:= &structEncoder
{
590 fieldEncs
: make([]encoderFunc
, len(fields
)),
592 for i
, f
:= range fields
{
593 se
.fieldEncs
[i
] = typeEncoder(typeByIndex(t
, f
.index
))
598 type mapEncoder
struct {
602 func (me
*mapEncoder
) encode(e
*encodeState
, v reflect
.Value
, _
bool) {
604 e
.WriteString("null")
608 var sv stringValues
= v
.MapKeys()
610 for i
, k
:= range sv
{
616 me
.elemEnc(e
, v
.MapIndex(k
), false)
621 func newMapEncoder(t reflect
.Type
) encoderFunc
{
622 if t
.Key().Kind() != reflect
.String
{
623 return unsupportedTypeEncoder
625 me
:= &mapEncoder
{typeEncoder(t
.Elem())}
629 func encodeByteSlice(e
*encodeState
, v reflect
.Value
, _
bool) {
631 e
.WriteString("null")
637 // for small buffers, using Encode directly is much faster.
638 dst
:= make([]byte, base64
.StdEncoding
.EncodedLen(len(s
)))
639 base64
.StdEncoding
.Encode(dst
, s
)
642 // for large buffers, avoid unnecessary extra temporary
644 enc
:= base64
.NewEncoder(base64
.StdEncoding
, e
)
651 // sliceEncoder just wraps an arrayEncoder, checking to make sure the value isn't nil.
652 type sliceEncoder
struct {
656 func (se
*sliceEncoder
) encode(e
*encodeState
, v reflect
.Value
, _
bool) {
658 e
.WriteString("null")
661 se
.arrayEnc(e
, v
, false)
664 func newSliceEncoder(t reflect
.Type
) encoderFunc
{
665 // Byte slices get special treatment; arrays don't.
666 if t
.Elem().Kind() == reflect
.Uint8
{
667 return encodeByteSlice
669 enc
:= &sliceEncoder
{newArrayEncoder(t
)}
673 type arrayEncoder
struct {
677 func (ae
*arrayEncoder
) encode(e
*encodeState
, v reflect
.Value
, _
bool) {
680 for i
:= 0; i
< n
; i
++ {
684 ae
.elemEnc(e
, v
.Index(i
), false)
689 func newArrayEncoder(t reflect
.Type
) encoderFunc
{
690 enc
:= &arrayEncoder
{typeEncoder(t
.Elem())}
694 type ptrEncoder
struct {
698 func (pe
*ptrEncoder
) encode(e
*encodeState
, v reflect
.Value
, _
bool) {
700 e
.WriteString("null")
703 pe
.elemEnc(e
, v
.Elem(), false)
706 func newPtrEncoder(t reflect
.Type
) encoderFunc
{
707 enc
:= &ptrEncoder
{typeEncoder(t
.Elem())}
711 type condAddrEncoder
struct {
712 canAddrEnc
, elseEnc encoderFunc
715 func (ce
*condAddrEncoder
) encode(e
*encodeState
, v reflect
.Value
, quoted
bool) {
717 ce
.canAddrEnc(e
, v
, quoted
)
719 ce
.elseEnc(e
, v
, quoted
)
723 // newCondAddrEncoder returns an encoder that checks whether its value
724 // CanAddr and delegates to canAddrEnc if so, else to elseEnc.
725 func newCondAddrEncoder(canAddrEnc
, elseEnc encoderFunc
) encoderFunc
{
726 enc
:= &condAddrEncoder
{canAddrEnc
: canAddrEnc
, elseEnc
: elseEnc
}
730 func isValidTag(s
string) bool {
734 for _
, c
:= range s
{
736 case strings
.ContainsRune("!#$%&()*+-./:<=>?@[]^_{|}~ ", c
):
737 // Backslash and quote chars are reserved, but
738 // otherwise any punctuation chars are allowed
741 if !unicode
.IsLetter(c
) && !unicode
.IsDigit(c
) {
749 func fieldByIndex(v reflect
.Value
, index
[]int) reflect
.Value
{
750 for _
, i
:= range index
{
751 if v
.Kind() == reflect
.Ptr
{
753 return reflect
.Value
{}
762 func typeByIndex(t reflect
.Type
, index
[]int) reflect
.Type
{
763 for _
, i
:= range index
{
764 if t
.Kind() == reflect
.Ptr
{
772 // stringValues is a slice of reflect.Value holding *reflect.StringValue.
773 // It implements the methods to sort by string.
774 type stringValues
[]reflect
.Value
776 func (sv stringValues
) Len() int { return len(sv
) }
777 func (sv stringValues
) Swap(i
, j
int) { sv
[i
], sv
[j
] = sv
[j
], sv
[i
] }
778 func (sv stringValues
) Less(i
, j
int) bool { return sv
.get(i
) < sv
.get(j
) }
779 func (sv stringValues
) get(i
int) string { return sv
[i
].String() }
781 // NOTE: keep in sync with stringBytes below.
782 func (e
*encodeState
) string(s
string) (int, error
) {
786 for i
:= 0; i
< len(s
); {
787 if b
:= s
[i
]; b
< utf8
.RuneSelf
{
788 if 0x20 <= b
&& b
!= '\\' && b
!= '"' && b
!= '<' && b
!= '>' && b
!= '&' {
793 e
.WriteString(s
[start
:i
])
806 // This encodes bytes < 0x20 except for \n and \r,
807 // as well as < and >. The latter are escaped because they
808 // can lead to security holes when user-controlled strings
809 // are rendered into JSON and served to some browsers.
810 e
.WriteString(`\u00`)
811 e
.WriteByte(hex
[b
>>4])
812 e
.WriteByte(hex
[b
&0xF])
818 c
, size
:= utf8
.DecodeRuneInString(s
[i
:])
819 if c
== utf8
.RuneError
&& size
== 1 {
821 e
.WriteString(s
[start
:i
])
823 e
.WriteString(`\ufffd`)
828 // U+2028 is LINE SEPARATOR.
829 // U+2029 is PARAGRAPH SEPARATOR.
830 // They are both technically valid characters in JSON strings,
831 // but don't work in JSONP, which has to be evaluated as JavaScript,
832 // and can lead to security holes there. It is valid JSON to
833 // escape them, so we do so unconditionally.
834 // See http://timelessrepo.com/json-isnt-a-javascript-subset for discussion.
835 if c
== '\u2028' || c
== '\u2029' {
837 e
.WriteString(s
[start
:i
])
839 e
.WriteString(`\u202`)
840 e
.WriteByte(hex
[c
&0xF])
848 e
.WriteString(s
[start
:])
851 return e
.Len() - len0
, nil
854 // NOTE: keep in sync with string above.
855 func (e
*encodeState
) stringBytes(s
[]byte) (int, error
) {
859 for i
:= 0; i
< len(s
); {
860 if b
:= s
[i
]; b
< utf8
.RuneSelf
{
861 if 0x20 <= b
&& b
!= '\\' && b
!= '"' && b
!= '<' && b
!= '>' && b
!= '&' {
879 // This encodes bytes < 0x20 except for \n and \r,
880 // as well as < and >. The latter are escaped because they
881 // can lead to security holes when user-controlled strings
882 // are rendered into JSON and served to some browsers.
883 e
.WriteString(`\u00`)
884 e
.WriteByte(hex
[b
>>4])
885 e
.WriteByte(hex
[b
&0xF])
891 c
, size
:= utf8
.DecodeRune(s
[i
:])
892 if c
== utf8
.RuneError
&& size
== 1 {
896 e
.WriteString(`\ufffd`)
901 // U+2028 is LINE SEPARATOR.
902 // U+2029 is PARAGRAPH SEPARATOR.
903 // They are both technically valid characters in JSON strings,
904 // but don't work in JSONP, which has to be evaluated as JavaScript,
905 // and can lead to security holes there. It is valid JSON to
906 // escape them, so we do so unconditionally.
907 // See http://timelessrepo.com/json-isnt-a-javascript-subset for discussion.
908 if c
== '\u2028' || c
== '\u2029' {
912 e
.WriteString(`\u202`)
913 e
.WriteByte(hex
[c
&0xF])
924 return e
.Len() - len0
, nil
927 // A field represents a single field found in a struct.
930 nameBytes
[]byte // []byte(name)
931 equalFold
func(s
, t
[]byte) bool // bytes.EqualFold or equivalent
940 func fillField(f field
) field
{
941 f
.nameBytes
= []byte(f
.name
)
942 f
.equalFold
= foldFunc(f
.nameBytes
)
946 // byName sorts field by name, breaking ties with depth,
947 // then breaking ties with "name came from json tag", then
948 // breaking ties with index sequence.
951 func (x byName
) Len() int { return len(x
) }
953 func (x byName
) Swap(i
, j
int) { x
[i
], x
[j
] = x
[j
], x
[i
] }
955 func (x byName
) Less(i
, j
int) bool {
956 if x
[i
].name
!= x
[j
].name
{
957 return x
[i
].name
< x
[j
].name
959 if len(x
[i
].index
) != len(x
[j
].index
) {
960 return len(x
[i
].index
) < len(x
[j
].index
)
962 if x
[i
].tag
!= x
[j
].tag
{
965 return byIndex(x
).Less(i
, j
)
968 // byIndex sorts field by index sequence.
971 func (x byIndex
) Len() int { return len(x
) }
973 func (x byIndex
) Swap(i
, j
int) { x
[i
], x
[j
] = x
[j
], x
[i
] }
975 func (x byIndex
) Less(i
, j
int) bool {
976 for k
, xik
:= range x
[i
].index
{
977 if k
>= len(x
[j
].index
) {
980 if xik
!= x
[j
].index
[k
] {
981 return xik
< x
[j
].index
[k
]
984 return len(x
[i
].index
) < len(x
[j
].index
)
987 // typeFields returns a list of fields that JSON should recognize for the given type.
988 // The algorithm is breadth-first search over the set of structs to include - the top struct
989 // and then any reachable anonymous structs.
990 func typeFields(t reflect
.Type
) []field
{
991 // Anonymous fields to explore at the current level and the next.
993 next
:= []field
{{typ
: t
}}
995 // Count of queued names for current level and the next.
996 count
:= map[reflect
.Type
]int{}
997 nextCount
:= map[reflect
.Type
]int{}
999 // Types already visited at an earlier level.
1000 visited
:= map[reflect
.Type
]bool{}
1006 current
, next
= next
, current
[:0]
1007 count
, nextCount
= nextCount
, map[reflect
.Type
]int{}
1009 for _
, f
:= range current
{
1013 visited
[f
.typ
] = true
1015 // Scan f.typ for fields to include.
1016 for i
:= 0; i
< f
.typ
.NumField(); i
++ {
1017 sf
:= f
.typ
.Field(i
)
1018 if sf
.PkgPath
!= "" { // unexported
1021 tag
:= sf
.Tag
.Get("json")
1025 name
, opts
:= parseTag(tag
)
1026 if !isValidTag(name
) {
1029 index
:= make([]int, len(f
.index
)+1)
1030 copy(index
, f
.index
)
1031 index
[len(f
.index
)] = i
1034 if ft
.Name() == "" && ft
.Kind() == reflect
.Ptr
{
1039 // Record found field and index sequence.
1040 if name
!= "" ||
!sf
.Anonymous || ft
.Kind() != reflect
.Struct
{
1041 tagged
:= name
!= ""
1045 fields
= append(fields
, fillField(field
{
1050 omitEmpty
: opts
.Contains("omitempty"),
1051 quoted
: opts
.Contains("string"),
1053 if count
[f
.typ
] > 1 {
1054 // If there were multiple instances, add a second,
1055 // so that the annihilation code will see a duplicate.
1056 // It only cares about the distinction between 1 or 2,
1057 // so don't bother generating any more copies.
1058 fields
= append(fields
, fields
[len(fields
)-1])
1063 // Record new anonymous struct to explore in next round.
1065 if nextCount
[ft
] == 1 {
1066 next
= append(next
, fillField(field
{name
: ft
.Name(), index
: index
, typ
: ft
}))
1072 sort
.Sort(byName(fields
))
1074 // Delete all fields that are hidden by the Go rules for embedded fields,
1075 // except that fields with JSON tags are promoted.
1077 // The fields are sorted in primary order of name, secondary order
1078 // of field index length. Loop over names; for each name, delete
1079 // hidden fields by choosing the one dominant field that survives.
1081 for advance
, i
:= 0, 0; i
< len(fields
); i
+= advance
{
1082 // One iteration per name.
1083 // Find the sequence of fields with the name of this first field.
1086 for advance
= 1; i
+advance
< len(fields
); advance
++ {
1087 fj
:= fields
[i
+advance
]
1088 if fj
.name
!= name
{
1092 if advance
== 1 { // Only one field with this name
1093 out
= append(out
, fi
)
1096 dominant
, ok
:= dominantField(fields
[i
: i
+advance
])
1098 out
= append(out
, dominant
)
1103 sort
.Sort(byIndex(fields
))
1108 // dominantField looks through the fields, all of which are known to
1109 // have the same name, to find the single field that dominates the
1110 // others using Go's embedding rules, modified by the presence of
1111 // JSON tags. If there are multiple top-level fields, the boolean
1112 // will be false: This condition is an error in Go and we skip all
1114 func dominantField(fields
[]field
) (field
, bool) {
1115 // The fields are sorted in increasing index-length order. The winner
1116 // must therefore be one with the shortest index length. Drop all
1117 // longer entries, which is easy: just truncate the slice.
1118 length
:= len(fields
[0].index
)
1119 tagged
:= -1 // Index of first tagged field.
1120 for i
, f
:= range fields
{
1121 if len(f
.index
) > length
{
1127 // Multiple tagged fields at the same level: conflict.
1129 return field
{}, false
1135 return fields
[tagged
], true
1137 // All remaining fields have the same length. If there's more than one,
1138 // we have a conflict (two fields named "X" at the same level) and we
1140 if len(fields
) > 1 {
1141 return field
{}, false
1143 return fields
[0], true
1146 var fieldCache
struct {
1148 m
map[reflect
.Type
][]field
1151 // cachedTypeFields is like typeFields but uses a cache to avoid repeated work.
1152 func cachedTypeFields(t reflect
.Type
) []field
{
1154 f
:= fieldCache
.m
[t
]
1155 fieldCache
.RUnlock()
1160 // Compute fields without lock.
1161 // Might duplicate effort but won't hold other computations back.
1168 if fieldCache
.m
== nil {
1169 fieldCache
.m
= map[reflect
.Type
][]field
{}