Home | History | Annotate | Download | only in json
      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.
      4 
      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.
      8 //
      9 // See "JSON and Go" for an introduction to this package:
     10 // https://golang.org/doc/articles/json_and_go.html
     11 package json
     12 
     13 import (
     14 	"bytes"
     15 	"encoding"
     16 	"encoding/base64"
     17 	"math"
     18 	"reflect"
     19 	"runtime"
     20 	"sort"
     21 	"strconv"
     22 	"strings"
     23 	"sync"
     24 	"unicode"
     25 	"unicode/utf8"
     26 )
     27 
     28 // Marshal returns the JSON encoding of v.
     29 //
     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
     35 // UnmarshalJSON.
     36 //
     37 // Otherwise, Marshal uses the following type-dependent default encodings:
     38 //
     39 // Boolean values encode as JSON booleans.
     40 //
     41 // Floating point, integer, and Number values encode as JSON numbers.
     42 //
     43 // String values encode as JSON strings coerced to valid UTF-8,
     44 // replacing invalid bytes with the Unicode replacement rune.
     45 // The angle brackets "<" and ">" are escaped to "\u003c" and "\u003e"
     46 // to keep some browsers from misinterpreting JSON output as HTML.
     47 // Ampersand "&" is also escaped to "\u0026" for the same reason.
     48 //
     49 // Array and slice values encode as JSON arrays, except that
     50 // []byte encodes as a base64-encoded string, and a nil slice
     51 // encodes as the null JSON object.
     52 //
     53 // Struct values encode as JSON objects. Each exported struct field
     54 // becomes a member of the object unless
     55 //   - the field's tag is "-", or
     56 //   - the field is empty and its tag specifies the "omitempty" option.
     57 // The empty values are false, 0, any
     58 // nil pointer or interface value, and any array, slice, map, or string of
     59 // length zero. The object's default key string is the struct field name
     60 // but can be specified in the struct field's tag value. The "json" key in
     61 // the struct field's tag value is the key name, followed by an optional comma
     62 // and options. Examples:
     63 //
     64 //   // Field is ignored by this package.
     65 //   Field int `json:"-"`
     66 //
     67 //   // Field appears in JSON as key "myName".
     68 //   Field int `json:"myName"`
     69 //
     70 //   // Field appears in JSON as key "myName" and
     71 //   // the field is omitted from the object if its value is empty,
     72 //   // as defined above.
     73 //   Field int `json:"myName,omitempty"`
     74 //
     75 //   // Field appears in JSON as key "Field" (the default), but
     76 //   // the field is skipped if empty.
     77 //   // Note the leading comma.
     78 //   Field int `json:",omitempty"`
     79 //
     80 // The "string" option signals that a field is stored as JSON inside a
     81 // JSON-encoded string. It applies only to fields of string, floating point,
     82 // integer, or boolean types. This extra level of encoding is sometimes used
     83 // when communicating with JavaScript programs:
     84 //
     85 //    Int64String int64 `json:",string"`
     86 //
     87 // The key name will be used if it's a non-empty string consisting of
     88 // only Unicode letters, digits, dollar signs, percent signs, hyphens,
     89 // underscores and slashes.
     90 //
     91 // Anonymous struct fields are usually marshaled as if their inner exported fields
     92 // were fields in the outer struct, subject to the usual Go visibility rules amended
     93 // as described in the next paragraph.
     94 // An anonymous struct field with a name given in its JSON tag is treated as
     95 // having that name, rather than being anonymous.
     96 // An anonymous struct field of interface type is treated the same as having
     97 // that type as its name, rather than being anonymous.
     98 //
     99 // The Go visibility rules for struct fields are amended for JSON when
    100 // deciding which field to marshal or unmarshal. If there are
    101 // multiple fields at the same level, and that level is the least
    102 // nested (and would therefore be the nesting level selected by the
    103 // usual Go rules), the following extra rules apply:
    104 //
    105 // 1) Of those fields, if any are JSON-tagged, only tagged fields are considered,
    106 // even if there are multiple untagged fields that would otherwise conflict.
    107 // 2) If there is exactly one field (tagged or not according to the first rule), that is selected.
    108 // 3) Otherwise there are multiple fields, and all are ignored; no error occurs.
    109 //
    110 // Handling of anonymous struct fields is new in Go 1.1.
    111 // Prior to Go 1.1, anonymous struct fields were ignored. To force ignoring of
    112 // an anonymous struct field in both current and earlier versions, give the field
    113 // a JSON tag of "-".
    114 //
    115 // Map values encode as JSON objects.
    116 // The map's key type must be string; the map keys are used as JSON object
    117 // keys, subject to the UTF-8 coercion described for string values above.
    118 //
    119 // Pointer values encode as the value pointed to.
    120 // A nil pointer encodes as the null JSON object.
    121 //
    122 // Interface values encode as the value contained in the interface.
    123 // A nil interface value encodes as the null JSON object.
    124 //
    125 // Channel, complex, and function values cannot be encoded in JSON.
    126 // Attempting to encode such a value causes Marshal to return
    127 // an UnsupportedTypeError.
    128 //
    129 // JSON cannot represent cyclic data structures and Marshal does not
    130 // handle them.  Passing cyclic structures to Marshal will result in
    131 // an infinite recursion.
    132 //
    133 func Marshal(v interface{}) ([]byte, error) {
    134 	e := &encodeState{}
    135 	err := e.marshal(v)
    136 	if err != nil {
    137 		return nil, err
    138 	}
    139 	return e.Bytes(), nil
    140 }
    141 
    142 // MarshalIndent is like Marshal but applies Indent to format the output.
    143 func MarshalIndent(v interface{}, prefix, indent string) ([]byte, error) {
    144 	b, err := Marshal(v)
    145 	if err != nil {
    146 		return nil, err
    147 	}
    148 	var buf bytes.Buffer
    149 	err = Indent(&buf, b, prefix, indent)
    150 	if err != nil {
    151 		return nil, err
    152 	}
    153 	return buf.Bytes(), nil
    154 }
    155 
    156 // HTMLEscape appends to dst the JSON-encoded src with <, >, &, U+2028 and U+2029
    157 // characters inside string literals changed to \u003c, \u003e, \u0026, \u2028, \u2029
    158 // so that the JSON will be safe to embed inside HTML <script> tags.
    159 // For historical reasons, web browsers don't honor standard HTML
    160 // escaping within <script> tags, so an alternative JSON encoding must
    161 // be used.
    162 func HTMLEscape(dst *bytes.Buffer, src []byte) {
    163 	// The characters can only appear in string literals,
    164 	// so just scan the string one byte at a time.
    165 	start := 0
    166 	for i, c := range src {
    167 		if c == '<' || c == '>' || c == '&' {
    168 			if start < i {
    169 				dst.Write(src[start:i])
    170 			}
    171 			dst.WriteString(`\u00`)
    172 			dst.WriteByte(hex[c>>4])
    173 			dst.WriteByte(hex[c&0xF])
    174 			start = i + 1
    175 		}
    176 		// Convert U+2028 and U+2029 (E2 80 A8 and E2 80 A9).
    177 		if c == 0xE2 && i+2 < len(src) && src[i+1] == 0x80 && src[i+2]&^1 == 0xA8 {
    178 			if start < i {
    179 				dst.Write(src[start:i])
    180 			}
    181 			dst.WriteString(`\u202`)
    182 			dst.WriteByte(hex[src[i+2]&0xF])
    183 			start = i + 3
    184 		}
    185 	}
    186 	if start < len(src) {
    187 		dst.Write(src[start:])
    188 	}
    189 }
    190 
    191 // Marshaler is the interface implemented by objects that
    192 // can marshal themselves into valid JSON.
    193 type Marshaler interface {
    194 	MarshalJSON() ([]byte, error)
    195 }
    196 
    197 // An UnsupportedTypeError is returned by Marshal when attempting
    198 // to encode an unsupported value type.
    199 type UnsupportedTypeError struct {
    200 	Type reflect.Type
    201 }
    202 
    203 func (e *UnsupportedTypeError) Error() string {
    204 	return "json: unsupported type: " + e.Type.String()
    205 }
    206 
    207 type UnsupportedValueError struct {
    208 	Value reflect.Value
    209 	Str   string
    210 }
    211 
    212 func (e *UnsupportedValueError) Error() string {
    213 	return "json: unsupported value: " + e.Str
    214 }
    215 
    216 // Before Go 1.2, an InvalidUTF8Error was returned by Marshal when
    217 // attempting to encode a string value with invalid UTF-8 sequences.
    218 // As of Go 1.2, Marshal instead coerces the string to valid UTF-8 by
    219 // replacing invalid bytes with the Unicode replacement rune U+FFFD.
    220 // This error is no longer generated but is kept for backwards compatibility
    221 // with programs that might mention it.
    222 type InvalidUTF8Error struct {
    223 	S string // the whole string value that caused the error
    224 }
    225 
    226 func (e *InvalidUTF8Error) Error() string {
    227 	return "json: invalid UTF-8 in string: " + strconv.Quote(e.S)
    228 }
    229 
    230 type MarshalerError struct {
    231 	Type reflect.Type
    232 	Err  error
    233 }
    234 
    235 func (e *MarshalerError) Error() string {
    236 	return "json: error calling MarshalJSON for type " + e.Type.String() + ": " + e.Err.Error()
    237 }
    238 
    239 var hex = "0123456789abcdef"
    240 
    241 // An encodeState encodes JSON into a bytes.Buffer.
    242 type encodeState struct {
    243 	bytes.Buffer // accumulated output
    244 	scratch      [64]byte
    245 }
    246 
    247 var encodeStatePool sync.Pool
    248 
    249 func newEncodeState() *encodeState {
    250 	if v := encodeStatePool.Get(); v != nil {
    251 		e := v.(*encodeState)
    252 		e.Reset()
    253 		return e
    254 	}
    255 	return new(encodeState)
    256 }
    257 
    258 func (e *encodeState) marshal(v interface{}) (err error) {
    259 	defer func() {
    260 		if r := recover(); r != nil {
    261 			if _, ok := r.(runtime.Error); ok {
    262 				panic(r)
    263 			}
    264 			if s, ok := r.(string); ok {
    265 				panic(s)
    266 			}
    267 			err = r.(error)
    268 		}
    269 	}()
    270 	e.reflectValue(reflect.ValueOf(v))
    271 	return nil
    272 }
    273 
    274 func (e *encodeState) error(err error) {
    275 	panic(err)
    276 }
    277 
    278 func isEmptyValue(v reflect.Value) bool {
    279 	switch v.Kind() {
    280 	case reflect.Array, reflect.Map, reflect.Slice, reflect.String:
    281 		return v.Len() == 0
    282 	case reflect.Bool:
    283 		return !v.Bool()
    284 	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
    285 		return v.Int() == 0
    286 	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
    287 		return v.Uint() == 0
    288 	case reflect.Float32, reflect.Float64:
    289 		return v.Float() == 0
    290 	case reflect.Interface, reflect.Ptr:
    291 		return v.IsNil()
    292 	}
    293 	return false
    294 }
    295 
    296 func (e *encodeState) reflectValue(v reflect.Value) {
    297 	valueEncoder(v)(e, v, false)
    298 }
    299 
    300 type encoderFunc func(e *encodeState, v reflect.Value, quoted bool)
    301 
    302 var encoderCache struct {
    303 	sync.RWMutex
    304 	m map[reflect.Type]encoderFunc
    305 }
    306 
    307 func valueEncoder(v reflect.Value) encoderFunc {
    308 	if !v.IsValid() {
    309 		return invalidValueEncoder
    310 	}
    311 	return typeEncoder(v.Type())
    312 }
    313 
    314 func typeEncoder(t reflect.Type) encoderFunc {
    315 	encoderCache.RLock()
    316 	f := encoderCache.m[t]
    317 	encoderCache.RUnlock()
    318 	if f != nil {
    319 		return f
    320 	}
    321 
    322 	// To deal with recursive types, populate the map with an
    323 	// indirect func before we build it. This type waits on the
    324 	// real func (f) to be ready and then calls it.  This indirect
    325 	// func is only used for recursive types.
    326 	encoderCache.Lock()
    327 	if encoderCache.m == nil {
    328 		encoderCache.m = make(map[reflect.Type]encoderFunc)
    329 	}
    330 	var wg sync.WaitGroup
    331 	wg.Add(1)
    332 	encoderCache.m[t] = func(e *encodeState, v reflect.Value, quoted bool) {
    333 		wg.Wait()
    334 		f(e, v, quoted)
    335 	}
    336 	encoderCache.Unlock()
    337 
    338 	// Compute fields without lock.
    339 	// Might duplicate effort but won't hold other computations back.
    340 	f = newTypeEncoder(t, true)
    341 	wg.Done()
    342 	encoderCache.Lock()
    343 	encoderCache.m[t] = f
    344 	encoderCache.Unlock()
    345 	return f
    346 }
    347 
    348 var (
    349 	marshalerType     = reflect.TypeOf(new(Marshaler)).Elem()
    350 	textMarshalerType = reflect.TypeOf(new(encoding.TextMarshaler)).Elem()
    351 )
    352 
    353 // newTypeEncoder constructs an encoderFunc for a type.
    354 // The returned encoder only checks CanAddr when allowAddr is true.
    355 func newTypeEncoder(t reflect.Type, allowAddr bool) encoderFunc {
    356 	if t.Implements(marshalerType) {
    357 		return marshalerEncoder
    358 	}
    359 	if t.Kind() != reflect.Ptr && allowAddr {
    360 		if reflect.PtrTo(t).Implements(marshalerType) {
    361 			return newCondAddrEncoder(addrMarshalerEncoder, newTypeEncoder(t, false))
    362 		}
    363 	}
    364 
    365 	if t.Implements(textMarshalerType) {
    366 		return textMarshalerEncoder
    367 	}
    368 	if t.Kind() != reflect.Ptr && allowAddr {
    369 		if reflect.PtrTo(t).Implements(textMarshalerType) {
    370 			return newCondAddrEncoder(addrTextMarshalerEncoder, newTypeEncoder(t, false))
    371 		}
    372 	}
    373 
    374 	switch t.Kind() {
    375 	case reflect.Bool:
    376 		return boolEncoder
    377 	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
    378 		return intEncoder
    379 	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
    380 		return uintEncoder
    381 	case reflect.Float32:
    382 		return float32Encoder
    383 	case reflect.Float64:
    384 		return float64Encoder
    385 	case reflect.String:
    386 		return stringEncoder
    387 	case reflect.Interface:
    388 		return interfaceEncoder
    389 	case reflect.Struct:
    390 		return newStructEncoder(t)
    391 	case reflect.Map:
    392 		return newMapEncoder(t)
    393 	case reflect.Slice:
    394 		return newSliceEncoder(t)
    395 	case reflect.Array:
    396 		return newArrayEncoder(t)
    397 	case reflect.Ptr:
    398 		return newPtrEncoder(t)
    399 	default:
    400 		return unsupportedTypeEncoder
    401 	}
    402 }
    403 
    404 func invalidValueEncoder(e *encodeState, v reflect.Value, quoted bool) {
    405 	e.WriteString("null")
    406 }
    407 
    408 func marshalerEncoder(e *encodeState, v reflect.Value, quoted bool) {
    409 	if v.Kind() == reflect.Ptr && v.IsNil() {
    410 		e.WriteString("null")
    411 		return
    412 	}
    413 	m := v.Interface().(Marshaler)
    414 	b, err := m.MarshalJSON()
    415 	if err == nil {
    416 		// copy JSON into buffer, checking validity.
    417 		err = compact(&e.Buffer, b, true)
    418 	}
    419 	if err != nil {
    420 		e.error(&MarshalerError{v.Type(), err})
    421 	}
    422 }
    423 
    424 func addrMarshalerEncoder(e *encodeState, v reflect.Value, quoted bool) {
    425 	va := v.Addr()
    426 	if va.IsNil() {
    427 		e.WriteString("null")
    428 		return
    429 	}
    430 	m := va.Interface().(Marshaler)
    431 	b, err := m.MarshalJSON()
    432 	if err == nil {
    433 		// copy JSON into buffer, checking validity.
    434 		err = compact(&e.Buffer, b, true)
    435 	}
    436 	if err != nil {
    437 		e.error(&MarshalerError{v.Type(), err})
    438 	}
    439 }
    440 
    441 func textMarshalerEncoder(e *encodeState, v reflect.Value, quoted bool) {
    442 	if v.Kind() == reflect.Ptr && v.IsNil() {
    443 		e.WriteString("null")
    444 		return
    445 	}
    446 	m := v.Interface().(encoding.TextMarshaler)
    447 	b, err := m.MarshalText()
    448 	if err == nil {
    449 		_, err = e.stringBytes(b)
    450 	}
    451 	if err != nil {
    452 		e.error(&MarshalerError{v.Type(), err})
    453 	}
    454 }
    455 
    456 func addrTextMarshalerEncoder(e *encodeState, v reflect.Value, quoted bool) {
    457 	va := v.Addr()
    458 	if va.IsNil() {
    459 		e.WriteString("null")
    460 		return
    461 	}
    462 	m := va.Interface().(encoding.TextMarshaler)
    463 	b, err := m.MarshalText()
    464 	if err == nil {
    465 		_, err = e.stringBytes(b)
    466 	}
    467 	if err != nil {
    468 		e.error(&MarshalerError{v.Type(), err})
    469 	}
    470 }
    471 
    472 func boolEncoder(e *encodeState, v reflect.Value, quoted bool) {
    473 	if quoted {
    474 		e.WriteByte('"')
    475 	}
    476 	if v.Bool() {
    477 		e.WriteString("true")
    478 	} else {
    479 		e.WriteString("false")
    480 	}
    481 	if quoted {
    482 		e.WriteByte('"')
    483 	}
    484 }
    485 
    486 func intEncoder(e *encodeState, v reflect.Value, quoted bool) {
    487 	b := strconv.AppendInt(e.scratch[:0], v.Int(), 10)
    488 	if quoted {
    489 		e.WriteByte('"')
    490 	}
    491 	e.Write(b)
    492 	if quoted {
    493 		e.WriteByte('"')
    494 	}
    495 }
    496 
    497 func uintEncoder(e *encodeState, v reflect.Value, quoted bool) {
    498 	b := strconv.AppendUint(e.scratch[:0], v.Uint(), 10)
    499 	if quoted {
    500 		e.WriteByte('"')
    501 	}
    502 	e.Write(b)
    503 	if quoted {
    504 		e.WriteByte('"')
    505 	}
    506 }
    507 
    508 type floatEncoder int // number of bits
    509 
    510 func (bits floatEncoder) encode(e *encodeState, v reflect.Value, quoted bool) {
    511 	f := v.Float()
    512 	if math.IsInf(f, 0) || math.IsNaN(f) {
    513 		e.error(&UnsupportedValueError{v, strconv.FormatFloat(f, 'g', -1, int(bits))})
    514 	}
    515 	b := strconv.AppendFloat(e.scratch[:0], f, 'g', -1, int(bits))
    516 	if quoted {
    517 		e.WriteByte('"')
    518 	}
    519 	e.Write(b)
    520 	if quoted {
    521 		e.WriteByte('"')
    522 	}
    523 }
    524 
    525 var (
    526 	float32Encoder = (floatEncoder(32)).encode
    527 	float64Encoder = (floatEncoder(64)).encode
    528 )
    529 
    530 func stringEncoder(e *encodeState, v reflect.Value, quoted bool) {
    531 	if v.Type() == numberType {
    532 		numStr := v.String()
    533 		if numStr == "" {
    534 			numStr = "0" // Number's zero-val
    535 		}
    536 		e.WriteString(numStr)
    537 		return
    538 	}
    539 	if quoted {
    540 		sb, err := Marshal(v.String())
    541 		if err != nil {
    542 			e.error(err)
    543 		}
    544 		e.string(string(sb))
    545 	} else {
    546 		e.string(v.String())
    547 	}
    548 }
    549 
    550 func interfaceEncoder(e *encodeState, v reflect.Value, quoted bool) {
    551 	if v.IsNil() {
    552 		e.WriteString("null")
    553 		return
    554 	}
    555 	e.reflectValue(v.Elem())
    556 }
    557 
    558 func unsupportedTypeEncoder(e *encodeState, v reflect.Value, quoted bool) {
    559 	e.error(&UnsupportedTypeError{v.Type()})
    560 }
    561 
    562 type structEncoder struct {
    563 	fields    []field
    564 	fieldEncs []encoderFunc
    565 }
    566 
    567 func (se *structEncoder) encode(e *encodeState, v reflect.Value, quoted bool) {
    568 	e.WriteByte('{')
    569 	first := true
    570 	for i, f := range se.fields {
    571 		fv := fieldByIndex(v, f.index)
    572 		if !fv.IsValid() || f.omitEmpty && isEmptyValue(fv) {
    573 			continue
    574 		}
    575 		if first {
    576 			first = false
    577 		} else {
    578 			e.WriteByte(',')
    579 		}
    580 		e.string(f.name)
    581 		e.WriteByte(':')
    582 		se.fieldEncs[i](e, fv, f.quoted)
    583 	}
    584 	e.WriteByte('}')
    585 }
    586 
    587 func newStructEncoder(t reflect.Type) encoderFunc {
    588 	fields := cachedTypeFields(t)
    589 	se := &structEncoder{
    590 		fields:    fields,
    591 		fieldEncs: make([]encoderFunc, len(fields)),
    592 	}
    593 	for i, f := range fields {
    594 		se.fieldEncs[i] = typeEncoder(typeByIndex(t, f.index))
    595 	}
    596 	return se.encode
    597 }
    598 
    599 type mapEncoder struct {
    600 	elemEnc encoderFunc
    601 }
    602 
    603 func (me *mapEncoder) encode(e *encodeState, v reflect.Value, _ bool) {
    604 	if v.IsNil() {
    605 		e.WriteString("null")
    606 		return
    607 	}
    608 	e.WriteByte('{')
    609 	var sv stringValues = v.MapKeys()
    610 	sort.Sort(sv)
    611 	for i, k := range sv {
    612 		if i > 0 {
    613 			e.WriteByte(',')
    614 		}
    615 		e.string(k.String())
    616 		e.WriteByte(':')
    617 		me.elemEnc(e, v.MapIndex(k), false)
    618 	}
    619 	e.WriteByte('}')
    620 }
    621 
    622 func newMapEncoder(t reflect.Type) encoderFunc {
    623 	if t.Key().Kind() != reflect.String {
    624 		return unsupportedTypeEncoder
    625 	}
    626 	me := &mapEncoder{typeEncoder(t.Elem())}
    627 	return me.encode
    628 }
    629 
    630 func encodeByteSlice(e *encodeState, v reflect.Value, _ bool) {
    631 	if v.IsNil() {
    632 		e.WriteString("null")
    633 		return
    634 	}
    635 	s := v.Bytes()
    636 	e.WriteByte('"')
    637 	if len(s) < 1024 {
    638 		// for small buffers, using Encode directly is much faster.
    639 		dst := make([]byte, base64.StdEncoding.EncodedLen(len(s)))
    640 		base64.StdEncoding.Encode(dst, s)
    641 		e.Write(dst)
    642 	} else {
    643 		// for large buffers, avoid unnecessary extra temporary
    644 		// buffer space.
    645 		enc := base64.NewEncoder(base64.StdEncoding, e)
    646 		enc.Write(s)
    647 		enc.Close()
    648 	}
    649 	e.WriteByte('"')
    650 }
    651 
    652 // sliceEncoder just wraps an arrayEncoder, checking to make sure the value isn't nil.
    653 type sliceEncoder struct {
    654 	arrayEnc encoderFunc
    655 }
    656 
    657 func (se *sliceEncoder) encode(e *encodeState, v reflect.Value, _ bool) {
    658 	if v.IsNil() {
    659 		e.WriteString("null")
    660 		return
    661 	}
    662 	se.arrayEnc(e, v, false)
    663 }
    664 
    665 func newSliceEncoder(t reflect.Type) encoderFunc {
    666 	// Byte slices get special treatment; arrays don't.
    667 	if t.Elem().Kind() == reflect.Uint8 {
    668 		return encodeByteSlice
    669 	}
    670 	enc := &sliceEncoder{newArrayEncoder(t)}
    671 	return enc.encode
    672 }
    673 
    674 type arrayEncoder struct {
    675 	elemEnc encoderFunc
    676 }
    677 
    678 func (ae *arrayEncoder) encode(e *encodeState, v reflect.Value, _ bool) {
    679 	e.WriteByte('[')
    680 	n := v.Len()
    681 	for i := 0; i < n; i++ {
    682 		if i > 0 {
    683 			e.WriteByte(',')
    684 		}
    685 		ae.elemEnc(e, v.Index(i), false)
    686 	}
    687 	e.WriteByte(']')
    688 }
    689 
    690 func newArrayEncoder(t reflect.Type) encoderFunc {
    691 	enc := &arrayEncoder{typeEncoder(t.Elem())}
    692 	return enc.encode
    693 }
    694 
    695 type ptrEncoder struct {
    696 	elemEnc encoderFunc
    697 }
    698 
    699 func (pe *ptrEncoder) encode(e *encodeState, v reflect.Value, quoted bool) {
    700 	if v.IsNil() {
    701 		e.WriteString("null")
    702 		return
    703 	}
    704 	pe.elemEnc(e, v.Elem(), quoted)
    705 }
    706 
    707 func newPtrEncoder(t reflect.Type) encoderFunc {
    708 	enc := &ptrEncoder{typeEncoder(t.Elem())}
    709 	return enc.encode
    710 }
    711 
    712 type condAddrEncoder struct {
    713 	canAddrEnc, elseEnc encoderFunc
    714 }
    715 
    716 func (ce *condAddrEncoder) encode(e *encodeState, v reflect.Value, quoted bool) {
    717 	if v.CanAddr() {
    718 		ce.canAddrEnc(e, v, quoted)
    719 	} else {
    720 		ce.elseEnc(e, v, quoted)
    721 	}
    722 }
    723 
    724 // newCondAddrEncoder returns an encoder that checks whether its value
    725 // CanAddr and delegates to canAddrEnc if so, else to elseEnc.
    726 func newCondAddrEncoder(canAddrEnc, elseEnc encoderFunc) encoderFunc {
    727 	enc := &condAddrEncoder{canAddrEnc: canAddrEnc, elseEnc: elseEnc}
    728 	return enc.encode
    729 }
    730 
    731 func isValidTag(s string) bool {
    732 	if s == "" {
    733 		return false
    734 	}
    735 	for _, c := range s {
    736 		switch {
    737 		case strings.ContainsRune("!#$%&()*+-./:<=>?@[]^_{|}~ ", c):
    738 			// Backslash and quote chars are reserved, but
    739 			// otherwise any punctuation chars are allowed
    740 			// in a tag name.
    741 		default:
    742 			if !unicode.IsLetter(c) && !unicode.IsDigit(c) {
    743 				return false
    744 			}
    745 		}
    746 	}
    747 	return true
    748 }
    749 
    750 func fieldByIndex(v reflect.Value, index []int) reflect.Value {
    751 	for _, i := range index {
    752 		if v.Kind() == reflect.Ptr {
    753 			if v.IsNil() {
    754 				return reflect.Value{}
    755 			}
    756 			v = v.Elem()
    757 		}
    758 		v = v.Field(i)
    759 	}
    760 	return v
    761 }
    762 
    763 func typeByIndex(t reflect.Type, index []int) reflect.Type {
    764 	for _, i := range index {
    765 		if t.Kind() == reflect.Ptr {
    766 			t = t.Elem()
    767 		}
    768 		t = t.Field(i).Type
    769 	}
    770 	return t
    771 }
    772 
    773 // stringValues is a slice of reflect.Value holding *reflect.StringValue.
    774 // It implements the methods to sort by string.
    775 type stringValues []reflect.Value
    776 
    777 func (sv stringValues) Len() int           { return len(sv) }
    778 func (sv stringValues) Swap(i, j int)      { sv[i], sv[j] = sv[j], sv[i] }
    779 func (sv stringValues) Less(i, j int) bool { return sv.get(i) < sv.get(j) }
    780 func (sv stringValues) get(i int) string   { return sv[i].String() }
    781 
    782 // NOTE: keep in sync with stringBytes below.
    783 func (e *encodeState) string(s string) (int, error) {
    784 	len0 := e.Len()
    785 	e.WriteByte('"')
    786 	start := 0
    787 	for i := 0; i < len(s); {
    788 		if b := s[i]; b < utf8.RuneSelf {
    789 			if 0x20 <= b && b != '\\' && b != '"' && b != '<' && b != '>' && b != '&' {
    790 				i++
    791 				continue
    792 			}
    793 			if start < i {
    794 				e.WriteString(s[start:i])
    795 			}
    796 			switch b {
    797 			case '\\', '"':
    798 				e.WriteByte('\\')
    799 				e.WriteByte(b)
    800 			case '\n':
    801 				e.WriteByte('\\')
    802 				e.WriteByte('n')
    803 			case '\r':
    804 				e.WriteByte('\\')
    805 				e.WriteByte('r')
    806 			case '\t':
    807 				e.WriteByte('\\')
    808 				e.WriteByte('t')
    809 			default:
    810 				// This encodes bytes < 0x20 except for \n and \r,
    811 				// as well as <, > and &. The latter are escaped because they
    812 				// can lead to security holes when user-controlled strings
    813 				// are rendered into JSON and served to some browsers.
    814 				e.WriteString(`\u00`)
    815 				e.WriteByte(hex[b>>4])
    816 				e.WriteByte(hex[b&0xF])
    817 			}
    818 			i++
    819 			start = i
    820 			continue
    821 		}
    822 		c, size := utf8.DecodeRuneInString(s[i:])
    823 		if c == utf8.RuneError && size == 1 {
    824 			if start < i {
    825 				e.WriteString(s[start:i])
    826 			}
    827 			e.WriteString(`\ufffd`)
    828 			i += size
    829 			start = i
    830 			continue
    831 		}
    832 		// U+2028 is LINE SEPARATOR.
    833 		// U+2029 is PARAGRAPH SEPARATOR.
    834 		// They are both technically valid characters in JSON strings,
    835 		// but don't work in JSONP, which has to be evaluated as JavaScript,
    836 		// and can lead to security holes there. It is valid JSON to
    837 		// escape them, so we do so unconditionally.
    838 		// See http://timelessrepo.com/json-isnt-a-javascript-subset for discussion.
    839 		if c == '\u2028' || c == '\u2029' {
    840 			if start < i {
    841 				e.WriteString(s[start:i])
    842 			}
    843 			e.WriteString(`\u202`)
    844 			e.WriteByte(hex[c&0xF])
    845 			i += size
    846 			start = i
    847 			continue
    848 		}
    849 		i += size
    850 	}
    851 	if start < len(s) {
    852 		e.WriteString(s[start:])
    853 	}
    854 	e.WriteByte('"')
    855 	return e.Len() - len0, nil
    856 }
    857 
    858 // NOTE: keep in sync with string above.
    859 func (e *encodeState) stringBytes(s []byte) (int, error) {
    860 	len0 := e.Len()
    861 	e.WriteByte('"')
    862 	start := 0
    863 	for i := 0; i < len(s); {
    864 		if b := s[i]; b < utf8.RuneSelf {
    865 			if 0x20 <= b && b != '\\' && b != '"' && b != '<' && b != '>' && b != '&' {
    866 				i++
    867 				continue
    868 			}
    869 			if start < i {
    870 				e.Write(s[start:i])
    871 			}
    872 			switch b {
    873 			case '\\', '"':
    874 				e.WriteByte('\\')
    875 				e.WriteByte(b)
    876 			case '\n':
    877 				e.WriteByte('\\')
    878 				e.WriteByte('n')
    879 			case '\r':
    880 				e.WriteByte('\\')
    881 				e.WriteByte('r')
    882 			case '\t':
    883 				e.WriteByte('\\')
    884 				e.WriteByte('t')
    885 			default:
    886 				// This encodes bytes < 0x20 except for \n and \r,
    887 				// as well as <, >, and &. The latter are escaped because they
    888 				// can lead to security holes when user-controlled strings
    889 				// are rendered into JSON and served to some browsers.
    890 				e.WriteString(`\u00`)
    891 				e.WriteByte(hex[b>>4])
    892 				e.WriteByte(hex[b&0xF])
    893 			}
    894 			i++
    895 			start = i
    896 			continue
    897 		}
    898 		c, size := utf8.DecodeRune(s[i:])
    899 		if c == utf8.RuneError && size == 1 {
    900 			if start < i {
    901 				e.Write(s[start:i])
    902 			}
    903 			e.WriteString(`\ufffd`)
    904 			i += size
    905 			start = i
    906 			continue
    907 		}
    908 		// U+2028 is LINE SEPARATOR.
    909 		// U+2029 is PARAGRAPH SEPARATOR.
    910 		// They are both technically valid characters in JSON strings,
    911 		// but don't work in JSONP, which has to be evaluated as JavaScript,
    912 		// and can lead to security holes there. It is valid JSON to
    913 		// escape them, so we do so unconditionally.
    914 		// See http://timelessrepo.com/json-isnt-a-javascript-subset for discussion.
    915 		if c == '\u2028' || c == '\u2029' {
    916 			if start < i {
    917 				e.Write(s[start:i])
    918 			}
    919 			e.WriteString(`\u202`)
    920 			e.WriteByte(hex[c&0xF])
    921 			i += size
    922 			start = i
    923 			continue
    924 		}
    925 		i += size
    926 	}
    927 	if start < len(s) {
    928 		e.Write(s[start:])
    929 	}
    930 	e.WriteByte('"')
    931 	return e.Len() - len0, nil
    932 }
    933 
    934 // A field represents a single field found in a struct.
    935 type field struct {
    936 	name      string
    937 	nameBytes []byte                 // []byte(name)
    938 	equalFold func(s, t []byte) bool // bytes.EqualFold or equivalent
    939 
    940 	tag       bool
    941 	index     []int
    942 	typ       reflect.Type
    943 	omitEmpty bool
    944 	quoted    bool
    945 }
    946 
    947 func fillField(f field) field {
    948 	f.nameBytes = []byte(f.name)
    949 	f.equalFold = foldFunc(f.nameBytes)
    950 	return f
    951 }
    952 
    953 // byName sorts field by name, breaking ties with depth,
    954 // then breaking ties with "name came from json tag", then
    955 // breaking ties with index sequence.
    956 type byName []field
    957 
    958 func (x byName) Len() int { return len(x) }
    959 
    960 func (x byName) Swap(i, j int) { x[i], x[j] = x[j], x[i] }
    961 
    962 func (x byName) Less(i, j int) bool {
    963 	if x[i].name != x[j].name {
    964 		return x[i].name < x[j].name
    965 	}
    966 	if len(x[i].index) != len(x[j].index) {
    967 		return len(x[i].index) < len(x[j].index)
    968 	}
    969 	if x[i].tag != x[j].tag {
    970 		return x[i].tag
    971 	}
    972 	return byIndex(x).Less(i, j)
    973 }
    974 
    975 // byIndex sorts field by index sequence.
    976 type byIndex []field
    977 
    978 func (x byIndex) Len() int { return len(x) }
    979 
    980 func (x byIndex) Swap(i, j int) { x[i], x[j] = x[j], x[i] }
    981 
    982 func (x byIndex) Less(i, j int) bool {
    983 	for k, xik := range x[i].index {
    984 		if k >= len(x[j].index) {
    985 			return false
    986 		}
    987 		if xik != x[j].index[k] {
    988 			return xik < x[j].index[k]
    989 		}
    990 	}
    991 	return len(x[i].index) < len(x[j].index)
    992 }
    993 
    994 // typeFields returns a list of fields that JSON should recognize for the given type.
    995 // The algorithm is breadth-first search over the set of structs to include - the top struct
    996 // and then any reachable anonymous structs.
    997 func typeFields(t reflect.Type) []field {
    998 	// Anonymous fields to explore at the current level and the next.
    999 	current := []field{}
   1000 	next := []field{{typ: t}}
   1001 
   1002 	// Count of queued names for current level and the next.
   1003 	count := map[reflect.Type]int{}
   1004 	nextCount := map[reflect.Type]int{}
   1005 
   1006 	// Types already visited at an earlier level.
   1007 	visited := map[reflect.Type]bool{}
   1008 
   1009 	// Fields found.
   1010 	var fields []field
   1011 
   1012 	for len(next) > 0 {
   1013 		current, next = next, current[:0]
   1014 		count, nextCount = nextCount, map[reflect.Type]int{}
   1015 
   1016 		for _, f := range current {
   1017 			if visited[f.typ] {
   1018 				continue
   1019 			}
   1020 			visited[f.typ] = true
   1021 
   1022 			// Scan f.typ for fields to include.
   1023 			for i := 0; i < f.typ.NumField(); i++ {
   1024 				sf := f.typ.Field(i)
   1025 				if sf.PkgPath != "" { // unexported
   1026 					continue
   1027 				}
   1028 				tag := sf.Tag.Get("json")
   1029 				if tag == "-" {
   1030 					continue
   1031 				}
   1032 				name, opts := parseTag(tag)
   1033 				if !isValidTag(name) {
   1034 					name = ""
   1035 				}
   1036 				index := make([]int, len(f.index)+1)
   1037 				copy(index, f.index)
   1038 				index[len(f.index)] = i
   1039 
   1040 				ft := sf.Type
   1041 				if ft.Name() == "" && ft.Kind() == reflect.Ptr {
   1042 					// Follow pointer.
   1043 					ft = ft.Elem()
   1044 				}
   1045 
   1046 				// Only strings, floats, integers, and booleans can be quoted.
   1047 				quoted := false
   1048 				if opts.Contains("string") {
   1049 					switch ft.Kind() {
   1050 					case reflect.Bool,
   1051 						reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
   1052 						reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64,
   1053 						reflect.Float32, reflect.Float64,
   1054 						reflect.String:
   1055 						quoted = true
   1056 					}
   1057 				}
   1058 
   1059 				// Record found field and index sequence.
   1060 				if name != "" || !sf.Anonymous || ft.Kind() != reflect.Struct {
   1061 					tagged := name != ""
   1062 					if name == "" {
   1063 						name = sf.Name
   1064 					}
   1065 					fields = append(fields, fillField(field{
   1066 						name:      name,
   1067 						tag:       tagged,
   1068 						index:     index,
   1069 						typ:       ft,
   1070 						omitEmpty: opts.Contains("omitempty"),
   1071 						quoted:    quoted,
   1072 					}))
   1073 					if count[f.typ] > 1 {
   1074 						// If there were multiple instances, add a second,
   1075 						// so that the annihilation code will see a duplicate.
   1076 						// It only cares about the distinction between 1 or 2,
   1077 						// so don't bother generating any more copies.
   1078 						fields = append(fields, fields[len(fields)-1])
   1079 					}
   1080 					continue
   1081 				}
   1082 
   1083 				// Record new anonymous struct to explore in next round.
   1084 				nextCount[ft]++
   1085 				if nextCount[ft] == 1 {
   1086 					next = append(next, fillField(field{name: ft.Name(), index: index, typ: ft}))
   1087 				}
   1088 			}
   1089 		}
   1090 	}
   1091 
   1092 	sort.Sort(byName(fields))
   1093 
   1094 	// Delete all fields that are hidden by the Go rules for embedded fields,
   1095 	// except that fields with JSON tags are promoted.
   1096 
   1097 	// The fields are sorted in primary order of name, secondary order
   1098 	// of field index length. Loop over names; for each name, delete
   1099 	// hidden fields by choosing the one dominant field that survives.
   1100 	out := fields[:0]
   1101 	for advance, i := 0, 0; i < len(fields); i += advance {
   1102 		// One iteration per name.
   1103 		// Find the sequence of fields with the name of this first field.
   1104 		fi := fields[i]
   1105 		name := fi.name
   1106 		for advance = 1; i+advance < len(fields); advance++ {
   1107 			fj := fields[i+advance]
   1108 			if fj.name != name {
   1109 				break
   1110 			}
   1111 		}
   1112 		if advance == 1 { // Only one field with this name
   1113 			out = append(out, fi)
   1114 			continue
   1115 		}
   1116 		dominant, ok := dominantField(fields[i : i+advance])
   1117 		if ok {
   1118 			out = append(out, dominant)
   1119 		}
   1120 	}
   1121 
   1122 	fields = out
   1123 	sort.Sort(byIndex(fields))
   1124 
   1125 	return fields
   1126 }
   1127 
   1128 // dominantField looks through the fields, all of which are known to
   1129 // have the same name, to find the single field that dominates the
   1130 // others using Go's embedding rules, modified by the presence of
   1131 // JSON tags. If there are multiple top-level fields, the boolean
   1132 // will be false: This condition is an error in Go and we skip all
   1133 // the fields.
   1134 func dominantField(fields []field) (field, bool) {
   1135 	// The fields are sorted in increasing index-length order. The winner
   1136 	// must therefore be one with the shortest index length. Drop all
   1137 	// longer entries, which is easy: just truncate the slice.
   1138 	length := len(fields[0].index)
   1139 	tagged := -1 // Index of first tagged field.
   1140 	for i, f := range fields {
   1141 		if len(f.index) > length {
   1142 			fields = fields[:i]
   1143 			break
   1144 		}
   1145 		if f.tag {
   1146 			if tagged >= 0 {
   1147 				// Multiple tagged fields at the same level: conflict.
   1148 				// Return no field.
   1149 				return field{}, false
   1150 			}
   1151 			tagged = i
   1152 		}
   1153 	}
   1154 	if tagged >= 0 {
   1155 		return fields[tagged], true
   1156 	}
   1157 	// All remaining fields have the same length. If there's more than one,
   1158 	// we have a conflict (two fields named "X" at the same level) and we
   1159 	// return no field.
   1160 	if len(fields) > 1 {
   1161 		return field{}, false
   1162 	}
   1163 	return fields[0], true
   1164 }
   1165 
   1166 var fieldCache struct {
   1167 	sync.RWMutex
   1168 	m map[reflect.Type][]field
   1169 }
   1170 
   1171 // cachedTypeFields is like typeFields but uses a cache to avoid repeated work.
   1172 func cachedTypeFields(t reflect.Type) []field {
   1173 	fieldCache.RLock()
   1174 	f := fieldCache.m[t]
   1175 	fieldCache.RUnlock()
   1176 	if f != nil {
   1177 		return f
   1178 	}
   1179 
   1180 	// Compute fields without lock.
   1181 	// Might duplicate effort but won't hold other computations back.
   1182 	f = typeFields(t)
   1183 	if f == nil {
   1184 		f = []field{}
   1185 	}
   1186 
   1187 	fieldCache.Lock()
   1188 	if fieldCache.m == nil {
   1189 		fieldCache.m = map[reflect.Type][]field{}
   1190 	}
   1191 	fieldCache.m[t] = f
   1192 	fieldCache.Unlock()
   1193 	return f
   1194 }
   1195