...
Run Format

Source file src/encoding/json/encode.go

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

View as plain text