...
Run Format

Source file src/encoding/json/decode.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  // Represents JSON data structure using native Go types: booleans, floats,
     6  // strings, arrays, and maps.
     7  
     8  package json
     9  
    10  import (
    11  	"bytes"
    12  	"encoding"
    13  	"encoding/base64"
    14  	"errors"
    15  	"fmt"
    16  	"reflect"
    17  	"strconv"
    18  	"unicode"
    19  	"unicode/utf16"
    20  	"unicode/utf8"
    21  )
    22  
    23  // Unmarshal parses the JSON-encoded data and stores the result
    24  // in the value pointed to by v. If v is nil or not a pointer,
    25  // Unmarshal returns an InvalidUnmarshalError.
    26  //
    27  // Unmarshal uses the inverse of the encodings that
    28  // Marshal uses, allocating maps, slices, and pointers as necessary,
    29  // with the following additional rules:
    30  //
    31  // To unmarshal JSON into a pointer, Unmarshal first handles the case of
    32  // the JSON being the JSON literal null. In that case, Unmarshal sets
    33  // the pointer to nil. Otherwise, Unmarshal unmarshals the JSON into
    34  // the value pointed at by the pointer. If the pointer is nil, Unmarshal
    35  // allocates a new value for it to point to.
    36  //
    37  // To unmarshal JSON into a value implementing the Unmarshaler interface,
    38  // Unmarshal calls that value's UnmarshalJSON method, including
    39  // when the input is a JSON null.
    40  // Otherwise, if the value implements encoding.TextUnmarshaler
    41  // and the input is a JSON quoted string, Unmarshal calls that value's
    42  // UnmarshalText method with the unquoted form of the string.
    43  //
    44  // To unmarshal JSON into a struct, Unmarshal matches incoming object
    45  // keys to the keys used by Marshal (either the struct field name or its tag),
    46  // preferring an exact match but also accepting a case-insensitive match. By
    47  // default, object keys which don't have a corresponding struct field are
    48  // ignored (see Decoder.DisallowUnknownFields for an alternative).
    49  //
    50  // To unmarshal JSON into an interface value,
    51  // Unmarshal stores one of these in the interface value:
    52  //
    53  //	bool, for JSON booleans
    54  //	float64, for JSON numbers
    55  //	string, for JSON strings
    56  //	[]interface{}, for JSON arrays
    57  //	map[string]interface{}, for JSON objects
    58  //	nil for JSON null
    59  //
    60  // To unmarshal a JSON array into a slice, Unmarshal resets the slice length
    61  // to zero and then appends each element to the slice.
    62  // As a special case, to unmarshal an empty JSON array into a slice,
    63  // Unmarshal replaces the slice with a new empty slice.
    64  //
    65  // To unmarshal a JSON array into a Go array, Unmarshal decodes
    66  // JSON array elements into corresponding Go array elements.
    67  // If the Go array is smaller than the JSON array,
    68  // the additional JSON array elements are discarded.
    69  // If the JSON array is smaller than the Go array,
    70  // the additional Go array elements are set to zero values.
    71  //
    72  // To unmarshal a JSON object into a map, Unmarshal first establishes a map to
    73  // use. If the map is nil, Unmarshal allocates a new map. Otherwise Unmarshal
    74  // reuses the existing map, keeping existing entries. Unmarshal then stores
    75  // key-value pairs from the JSON object into the map. The map's key type must
    76  // either be a string, an integer, or implement encoding.TextUnmarshaler.
    77  //
    78  // If a JSON value is not appropriate for a given target type,
    79  // or if a JSON number overflows the target type, Unmarshal
    80  // skips that field and completes the unmarshaling as best it can.
    81  // If no more serious errors are encountered, Unmarshal returns
    82  // an UnmarshalTypeError describing the earliest such error. In any
    83  // case, it's not guaranteed that all the remaining fields following
    84  // the problematic one will be unmarshaled into the target object.
    85  //
    86  // The JSON null value unmarshals into an interface, map, pointer, or slice
    87  // by setting that Go value to nil. Because null is often used in JSON to mean
    88  // ``not present,'' unmarshaling a JSON null into any other Go type has no effect
    89  // on the value and produces no error.
    90  //
    91  // When unmarshaling quoted strings, invalid UTF-8 or
    92  // invalid UTF-16 surrogate pairs are not treated as an error.
    93  // Instead, they are replaced by the Unicode replacement
    94  // character U+FFFD.
    95  //
    96  func Unmarshal(data []byte, v interface{}) error {
    97  	// Check for well-formedness.
    98  	// Avoids filling out half a data structure
    99  	// before discovering a JSON syntax error.
   100  	var d decodeState
   101  	err := checkValid(data, &d.scan)
   102  	if err != nil {
   103  		return err
   104  	}
   105  
   106  	d.init(data)
   107  	return d.unmarshal(v)
   108  }
   109  
   110  // Unmarshaler is the interface implemented by types
   111  // that can unmarshal a JSON description of themselves.
   112  // The input can be assumed to be a valid encoding of
   113  // a JSON value. UnmarshalJSON must copy the JSON data
   114  // if it wishes to retain the data after returning.
   115  //
   116  // By convention, to approximate the behavior of Unmarshal itself,
   117  // Unmarshalers implement UnmarshalJSON([]byte("null")) as a no-op.
   118  type Unmarshaler interface {
   119  	UnmarshalJSON([]byte) error
   120  }
   121  
   122  // An UnmarshalTypeError describes a JSON value that was
   123  // not appropriate for a value of a specific Go type.
   124  type UnmarshalTypeError struct {
   125  	Value  string       // description of JSON value - "bool", "array", "number -5"
   126  	Type   reflect.Type // type of Go value it could not be assigned to
   127  	Offset int64        // error occurred after reading Offset bytes
   128  	Struct string       // name of the struct type containing the field
   129  	Field  string       // name of the field holding the Go value
   130  }
   131  
   132  func (e *UnmarshalTypeError) Error() string {
   133  	if e.Struct != "" || e.Field != "" {
   134  		return "json: cannot unmarshal " + e.Value + " into Go struct field " + e.Struct + "." + e.Field + " of type " + e.Type.String()
   135  	}
   136  	return "json: cannot unmarshal " + e.Value + " into Go value of type " + e.Type.String()
   137  }
   138  
   139  // An UnmarshalFieldError describes a JSON object key that
   140  // led to an unexported (and therefore unwritable) struct field.
   141  //
   142  // Deprecated: No longer used; kept for compatibility.
   143  type UnmarshalFieldError struct {
   144  	Key   string
   145  	Type  reflect.Type
   146  	Field reflect.StructField
   147  }
   148  
   149  func (e *UnmarshalFieldError) Error() string {
   150  	return "json: cannot unmarshal object key " + strconv.Quote(e.Key) + " into unexported field " + e.Field.Name + " of type " + e.Type.String()
   151  }
   152  
   153  // An InvalidUnmarshalError describes an invalid argument passed to Unmarshal.
   154  // (The argument to Unmarshal must be a non-nil pointer.)
   155  type InvalidUnmarshalError struct {
   156  	Type reflect.Type
   157  }
   158  
   159  func (e *InvalidUnmarshalError) Error() string {
   160  	if e.Type == nil {
   161  		return "json: Unmarshal(nil)"
   162  	}
   163  
   164  	if e.Type.Kind() != reflect.Ptr {
   165  		return "json: Unmarshal(non-pointer " + e.Type.String() + ")"
   166  	}
   167  	return "json: Unmarshal(nil " + e.Type.String() + ")"
   168  }
   169  
   170  func (d *decodeState) unmarshal(v interface{}) error {
   171  	rv := reflect.ValueOf(v)
   172  	if rv.Kind() != reflect.Ptr || rv.IsNil() {
   173  		return &InvalidUnmarshalError{reflect.TypeOf(v)}
   174  	}
   175  
   176  	d.scan.reset()
   177  	d.scanWhile(scanSkipSpace)
   178  	// We decode rv not rv.Elem because the Unmarshaler interface
   179  	// test must be applied at the top level of the value.
   180  	err := d.value(rv)
   181  	if err != nil {
   182  		return err
   183  	}
   184  	return d.savedError
   185  }
   186  
   187  // A Number represents a JSON number literal.
   188  type Number string
   189  
   190  // String returns the literal text of the number.
   191  func (n Number) String() string { return string(n) }
   192  
   193  // Float64 returns the number as a float64.
   194  func (n Number) Float64() (float64, error) {
   195  	return strconv.ParseFloat(string(n), 64)
   196  }
   197  
   198  // Int64 returns the number as an int64.
   199  func (n Number) Int64() (int64, error) {
   200  	return strconv.ParseInt(string(n), 10, 64)
   201  }
   202  
   203  // isValidNumber reports whether s is a valid JSON number literal.
   204  func isValidNumber(s string) bool {
   205  	// This function implements the JSON numbers grammar.
   206  	// See https://tools.ietf.org/html/rfc7159#section-6
   207  	// and https://json.org/number.gif
   208  
   209  	if s == "" {
   210  		return false
   211  	}
   212  
   213  	// Optional -
   214  	if s[0] == '-' {
   215  		s = s[1:]
   216  		if s == "" {
   217  			return false
   218  		}
   219  	}
   220  
   221  	// Digits
   222  	switch {
   223  	default:
   224  		return false
   225  
   226  	case s[0] == '0':
   227  		s = s[1:]
   228  
   229  	case '1' <= s[0] && s[0] <= '9':
   230  		s = s[1:]
   231  		for len(s) > 0 && '0' <= s[0] && s[0] <= '9' {
   232  			s = s[1:]
   233  		}
   234  	}
   235  
   236  	// . followed by 1 or more digits.
   237  	if len(s) >= 2 && s[0] == '.' && '0' <= s[1] && s[1] <= '9' {
   238  		s = s[2:]
   239  		for len(s) > 0 && '0' <= s[0] && s[0] <= '9' {
   240  			s = s[1:]
   241  		}
   242  	}
   243  
   244  	// e or E followed by an optional - or + and
   245  	// 1 or more digits.
   246  	if len(s) >= 2 && (s[0] == 'e' || s[0] == 'E') {
   247  		s = s[1:]
   248  		if s[0] == '+' || s[0] == '-' {
   249  			s = s[1:]
   250  			if s == "" {
   251  				return false
   252  			}
   253  		}
   254  		for len(s) > 0 && '0' <= s[0] && s[0] <= '9' {
   255  			s = s[1:]
   256  		}
   257  	}
   258  
   259  	// Make sure we are at the end.
   260  	return s == ""
   261  }
   262  
   263  // decodeState represents the state while decoding a JSON value.
   264  type decodeState struct {
   265  	data         []byte
   266  	off          int // next read offset in data
   267  	opcode       int // last read result
   268  	scan         scanner
   269  	errorContext struct { // provides context for type errors
   270  		Struct string
   271  		Field  string
   272  	}
   273  	savedError            error
   274  	useNumber             bool
   275  	disallowUnknownFields bool
   276  }
   277  
   278  // readIndex returns the position of the last byte read.
   279  func (d *decodeState) readIndex() int {
   280  	return d.off - 1
   281  }
   282  
   283  // errPhase is used for errors that should not happen unless
   284  // there is a bug in the JSON decoder or something is editing
   285  // the data slice while the decoder executes.
   286  var errPhase = errors.New("JSON decoder out of sync - data changing underfoot?")
   287  
   288  func (d *decodeState) init(data []byte) *decodeState {
   289  	d.data = data
   290  	d.off = 0
   291  	d.savedError = nil
   292  	d.errorContext.Struct = ""
   293  	d.errorContext.Field = ""
   294  	return d
   295  }
   296  
   297  // saveError saves the first err it is called with,
   298  // for reporting at the end of the unmarshal.
   299  func (d *decodeState) saveError(err error) {
   300  	if d.savedError == nil {
   301  		d.savedError = d.addErrorContext(err)
   302  	}
   303  }
   304  
   305  // addErrorContext returns a new error enhanced with information from d.errorContext
   306  func (d *decodeState) addErrorContext(err error) error {
   307  	if d.errorContext.Struct != "" || d.errorContext.Field != "" {
   308  		switch err := err.(type) {
   309  		case *UnmarshalTypeError:
   310  			err.Struct = d.errorContext.Struct
   311  			err.Field = d.errorContext.Field
   312  			return err
   313  		}
   314  	}
   315  	return err
   316  }
   317  
   318  // skip scans to the end of what was started.
   319  func (d *decodeState) skip() {
   320  	s, data, i := &d.scan, d.data, d.off
   321  	depth := len(s.parseState)
   322  	for {
   323  		op := s.step(s, data[i])
   324  		i++
   325  		if len(s.parseState) < depth {
   326  			d.off = i
   327  			d.opcode = op
   328  			return
   329  		}
   330  	}
   331  }
   332  
   333  // scanNext processes the byte at d.data[d.off].
   334  func (d *decodeState) scanNext() {
   335  	s, data, i := &d.scan, d.data, d.off
   336  	if i < len(data) {
   337  		d.opcode = s.step(s, data[i])
   338  		d.off = i + 1
   339  	} else {
   340  		d.opcode = s.eof()
   341  		d.off = len(data) + 1 // mark processed EOF with len+1
   342  	}
   343  }
   344  
   345  // scanWhile processes bytes in d.data[d.off:] until it
   346  // receives a scan code not equal to op.
   347  func (d *decodeState) scanWhile(op int) {
   348  	s, data, i := &d.scan, d.data, d.off
   349  	for i < len(d.data) {
   350  		newOp := s.step(s, data[i])
   351  		i++
   352  		if newOp != op {
   353  			d.opcode = newOp
   354  			d.off = i
   355  			return
   356  		}
   357  	}
   358  
   359  	d.off = len(d.data) + 1 // mark processed EOF with len+1
   360  	d.opcode = d.scan.eof()
   361  }
   362  
   363  // value consumes a JSON value from d.data[d.off-1:], decoding into v, and
   364  // reads the following byte ahead. If v is invalid, the value is discarded.
   365  // The first byte of the value has been read already.
   366  func (d *decodeState) value(v reflect.Value) error {
   367  	switch d.opcode {
   368  	default:
   369  		return errPhase
   370  
   371  	case scanBeginArray:
   372  		if v.IsValid() {
   373  			if err := d.array(v); err != nil {
   374  				return err
   375  			}
   376  		} else {
   377  			d.skip()
   378  		}
   379  		d.scanNext()
   380  
   381  	case scanBeginObject:
   382  		if v.IsValid() {
   383  			if err := d.object(v); err != nil {
   384  				return err
   385  			}
   386  		} else {
   387  			d.skip()
   388  		}
   389  		d.scanNext()
   390  
   391  	case scanBeginLiteral:
   392  		// All bytes inside literal return scanContinue op code.
   393  		start := d.readIndex()
   394  		d.scanWhile(scanContinue)
   395  
   396  		if v.IsValid() {
   397  			if err := d.literalStore(d.data[start:d.readIndex()], v, false); err != nil {
   398  				return err
   399  			}
   400  		}
   401  	}
   402  	return nil
   403  }
   404  
   405  type unquotedValue struct{}
   406  
   407  // valueQuoted is like value but decodes a
   408  // quoted string literal or literal null into an interface value.
   409  // If it finds anything other than a quoted string literal or null,
   410  // valueQuoted returns unquotedValue{}.
   411  func (d *decodeState) valueQuoted() (interface{}, error) {
   412  	switch d.opcode {
   413  	default:
   414  		return nil, errPhase
   415  
   416  	case scanBeginArray:
   417  		d.skip()
   418  		d.scanNext()
   419  
   420  	case scanBeginObject:
   421  		d.skip()
   422  		d.scanNext()
   423  
   424  	case scanBeginLiteral:
   425  		v, err := d.literalInterface()
   426  		if err != nil {
   427  			return nil, err
   428  		}
   429  		switch v.(type) {
   430  		case nil, string:
   431  			return v, nil
   432  		}
   433  	}
   434  	return unquotedValue{}, nil
   435  }
   436  
   437  // indirect walks down v allocating pointers as needed,
   438  // until it gets to a non-pointer.
   439  // if it encounters an Unmarshaler, indirect stops and returns that.
   440  // if decodingNull is true, indirect stops at the last pointer so it can be set to nil.
   441  func indirect(v reflect.Value, decodingNull bool) (Unmarshaler, encoding.TextUnmarshaler, reflect.Value) {
   442  	// Issue #24153 indicates that it is generally not a guaranteed property
   443  	// that you may round-trip a reflect.Value by calling Value.Addr().Elem()
   444  	// and expect the value to still be settable for values derived from
   445  	// unexported embedded struct fields.
   446  	//
   447  	// The logic below effectively does this when it first addresses the value
   448  	// (to satisfy possible pointer methods) and continues to dereference
   449  	// subsequent pointers as necessary.
   450  	//
   451  	// After the first round-trip, we set v back to the original value to
   452  	// preserve the original RW flags contained in reflect.Value.
   453  	v0 := v
   454  	haveAddr := false
   455  
   456  	// If v is a named type and is addressable,
   457  	// start with its address, so that if the type has pointer methods,
   458  	// we find them.
   459  	if v.Kind() != reflect.Ptr && v.Type().Name() != "" && v.CanAddr() {
   460  		haveAddr = true
   461  		v = v.Addr()
   462  	}
   463  	for {
   464  		// Load value from interface, but only if the result will be
   465  		// usefully addressable.
   466  		if v.Kind() == reflect.Interface && !v.IsNil() {
   467  			e := v.Elem()
   468  			if e.Kind() == reflect.Ptr && !e.IsNil() && (!decodingNull || e.Elem().Kind() == reflect.Ptr) {
   469  				haveAddr = false
   470  				v = e
   471  				continue
   472  			}
   473  		}
   474  
   475  		if v.Kind() != reflect.Ptr {
   476  			break
   477  		}
   478  
   479  		if v.Elem().Kind() != reflect.Ptr && decodingNull && v.CanSet() {
   480  			break
   481  		}
   482  		if v.IsNil() {
   483  			v.Set(reflect.New(v.Type().Elem()))
   484  		}
   485  		if v.Type().NumMethod() > 0 {
   486  			if u, ok := v.Interface().(Unmarshaler); ok {
   487  				return u, nil, reflect.Value{}
   488  			}
   489  			if !decodingNull {
   490  				if u, ok := v.Interface().(encoding.TextUnmarshaler); ok {
   491  					return nil, u, reflect.Value{}
   492  				}
   493  			}
   494  		}
   495  
   496  		if haveAddr {
   497  			v = v0 // restore original value after round-trip Value.Addr().Elem()
   498  			haveAddr = false
   499  		} else {
   500  			v = v.Elem()
   501  		}
   502  	}
   503  	return nil, nil, v
   504  }
   505  
   506  // array consumes an array from d.data[d.off-1:], decoding into v.
   507  // The first byte of the array ('[') has been read already.
   508  func (d *decodeState) array(v reflect.Value) error {
   509  	// Check for unmarshaler.
   510  	u, ut, pv := indirect(v, false)
   511  	if u != nil {
   512  		start := d.readIndex()
   513  		d.skip()
   514  		return u.UnmarshalJSON(d.data[start:d.off])
   515  	}
   516  	if ut != nil {
   517  		d.saveError(&UnmarshalTypeError{Value: "array", Type: v.Type(), Offset: int64(d.off)})
   518  		d.skip()
   519  		return nil
   520  	}
   521  	v = pv
   522  
   523  	// Check type of target.
   524  	switch v.Kind() {
   525  	case reflect.Interface:
   526  		if v.NumMethod() == 0 {
   527  			// Decoding into nil interface? Switch to non-reflect code.
   528  			ai, err := d.arrayInterface()
   529  			if err != nil {
   530  				return err
   531  			}
   532  			v.Set(reflect.ValueOf(ai))
   533  			return nil
   534  		}
   535  		// Otherwise it's invalid.
   536  		fallthrough
   537  	default:
   538  		d.saveError(&UnmarshalTypeError{Value: "array", Type: v.Type(), Offset: int64(d.off)})
   539  		d.skip()
   540  		return nil
   541  	case reflect.Array:
   542  	case reflect.Slice:
   543  		break
   544  	}
   545  
   546  	i := 0
   547  	for {
   548  		// Look ahead for ] - can only happen on first iteration.
   549  		d.scanWhile(scanSkipSpace)
   550  		if d.opcode == scanEndArray {
   551  			break
   552  		}
   553  
   554  		// Get element of array, growing if necessary.
   555  		if v.Kind() == reflect.Slice {
   556  			// Grow slice if necessary
   557  			if i >= v.Cap() {
   558  				newcap := v.Cap() + v.Cap()/2
   559  				if newcap < 4 {
   560  					newcap = 4
   561  				}
   562  				newv := reflect.MakeSlice(v.Type(), v.Len(), newcap)
   563  				reflect.Copy(newv, v)
   564  				v.Set(newv)
   565  			}
   566  			if i >= v.Len() {
   567  				v.SetLen(i + 1)
   568  			}
   569  		}
   570  
   571  		if i < v.Len() {
   572  			// Decode into element.
   573  			if err := d.value(v.Index(i)); err != nil {
   574  				return err
   575  			}
   576  		} else {
   577  			// Ran out of fixed array: skip.
   578  			if err := d.value(reflect.Value{}); err != nil {
   579  				return err
   580  			}
   581  		}
   582  		i++
   583  
   584  		// Next token must be , or ].
   585  		if d.opcode == scanSkipSpace {
   586  			d.scanWhile(scanSkipSpace)
   587  		}
   588  		if d.opcode == scanEndArray {
   589  			break
   590  		}
   591  		if d.opcode != scanArrayValue {
   592  			return errPhase
   593  		}
   594  	}
   595  
   596  	if i < v.Len() {
   597  		if v.Kind() == reflect.Array {
   598  			// Array. Zero the rest.
   599  			z := reflect.Zero(v.Type().Elem())
   600  			for ; i < v.Len(); i++ {
   601  				v.Index(i).Set(z)
   602  			}
   603  		} else {
   604  			v.SetLen(i)
   605  		}
   606  	}
   607  	if i == 0 && v.Kind() == reflect.Slice {
   608  		v.Set(reflect.MakeSlice(v.Type(), 0, 0))
   609  	}
   610  	return nil
   611  }
   612  
   613  var nullLiteral = []byte("null")
   614  var textUnmarshalerType = reflect.TypeOf(new(encoding.TextUnmarshaler)).Elem()
   615  
   616  // object consumes an object from d.data[d.off-1:], decoding into v.
   617  // The first byte ('{') of the object has been read already.
   618  func (d *decodeState) object(v reflect.Value) error {
   619  	// Check for unmarshaler.
   620  	u, ut, pv := indirect(v, false)
   621  	if u != nil {
   622  		start := d.readIndex()
   623  		d.skip()
   624  		return u.UnmarshalJSON(d.data[start:d.off])
   625  	}
   626  	if ut != nil {
   627  		d.saveError(&UnmarshalTypeError{Value: "object", Type: v.Type(), Offset: int64(d.off)})
   628  		d.skip()
   629  		return nil
   630  	}
   631  	v = pv
   632  
   633  	// Decoding into nil interface? Switch to non-reflect code.
   634  	if v.Kind() == reflect.Interface && v.NumMethod() == 0 {
   635  		oi, err := d.objectInterface()
   636  		if err != nil {
   637  			return err
   638  		}
   639  		v.Set(reflect.ValueOf(oi))
   640  		return nil
   641  	}
   642  
   643  	// Check type of target:
   644  	//   struct or
   645  	//   map[T1]T2 where T1 is string, an integer type,
   646  	//             or an encoding.TextUnmarshaler
   647  	switch v.Kind() {
   648  	case reflect.Map:
   649  		// Map key must either have string kind, have an integer kind,
   650  		// or be an encoding.TextUnmarshaler.
   651  		t := v.Type()
   652  		switch t.Key().Kind() {
   653  		case reflect.String,
   654  			reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
   655  			reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
   656  		default:
   657  			if !reflect.PtrTo(t.Key()).Implements(textUnmarshalerType) {
   658  				d.saveError(&UnmarshalTypeError{Value: "object", Type: v.Type(), Offset: int64(d.off)})
   659  				d.skip()
   660  				return nil
   661  			}
   662  		}
   663  		if v.IsNil() {
   664  			v.Set(reflect.MakeMap(t))
   665  		}
   666  	case reflect.Struct:
   667  		// ok
   668  	default:
   669  		d.saveError(&UnmarshalTypeError{Value: "object", Type: v.Type(), Offset: int64(d.off)})
   670  		d.skip()
   671  		return nil
   672  	}
   673  
   674  	var mapElem reflect.Value
   675  	originalErrorContext := d.errorContext
   676  
   677  	for {
   678  		// Read opening " of string key or closing }.
   679  		d.scanWhile(scanSkipSpace)
   680  		if d.opcode == scanEndObject {
   681  			// closing } - can only happen on first iteration.
   682  			break
   683  		}
   684  		if d.opcode != scanBeginLiteral {
   685  			return errPhase
   686  		}
   687  
   688  		// Read key.
   689  		start := d.readIndex()
   690  		d.scanWhile(scanContinue)
   691  		item := d.data[start:d.readIndex()]
   692  		key, ok := unquoteBytes(item)
   693  		if !ok {
   694  			return errPhase
   695  		}
   696  
   697  		// Figure out field corresponding to key.
   698  		var subv reflect.Value
   699  		destring := false // whether the value is wrapped in a string to be decoded first
   700  
   701  		if v.Kind() == reflect.Map {
   702  			elemType := v.Type().Elem()
   703  			if !mapElem.IsValid() {
   704  				mapElem = reflect.New(elemType).Elem()
   705  			} else {
   706  				mapElem.Set(reflect.Zero(elemType))
   707  			}
   708  			subv = mapElem
   709  		} else {
   710  			var f *field
   711  			fields := cachedTypeFields(v.Type())
   712  			for i := range fields {
   713  				ff := &fields[i]
   714  				if bytes.Equal(ff.nameBytes, key) {
   715  					f = ff
   716  					break
   717  				}
   718  				if f == nil && ff.equalFold(ff.nameBytes, key) {
   719  					f = ff
   720  				}
   721  			}
   722  			if f != nil {
   723  				subv = v
   724  				destring = f.quoted
   725  				for _, i := range f.index {
   726  					if subv.Kind() == reflect.Ptr {
   727  						if subv.IsNil() {
   728  							// If a struct embeds a pointer to an unexported type,
   729  							// it is not possible to set a newly allocated value
   730  							// since the field is unexported.
   731  							//
   732  							// See https://golang.org/issue/21357
   733  							if !subv.CanSet() {
   734  								d.saveError(fmt.Errorf("json: cannot set embedded pointer to unexported struct: %v", subv.Type().Elem()))
   735  								// Invalidate subv to ensure d.value(subv) skips over
   736  								// the JSON value without assigning it to subv.
   737  								subv = reflect.Value{}
   738  								destring = false
   739  								break
   740  							}
   741  							subv.Set(reflect.New(subv.Type().Elem()))
   742  						}
   743  						subv = subv.Elem()
   744  					}
   745  					subv = subv.Field(i)
   746  				}
   747  				d.errorContext.Field = f.name
   748  				d.errorContext.Struct = v.Type().Name()
   749  			} else if d.disallowUnknownFields {
   750  				d.saveError(fmt.Errorf("json: unknown field %q", key))
   751  			}
   752  		}
   753  
   754  		// Read : before value.
   755  		if d.opcode == scanSkipSpace {
   756  			d.scanWhile(scanSkipSpace)
   757  		}
   758  		if d.opcode != scanObjectKey {
   759  			return errPhase
   760  		}
   761  		d.scanWhile(scanSkipSpace)
   762  
   763  		if destring {
   764  			q, err := d.valueQuoted()
   765  			if err != nil {
   766  				return err
   767  			}
   768  			switch qv := q.(type) {
   769  			case nil:
   770  				if err := d.literalStore(nullLiteral, subv, false); err != nil {
   771  					return err
   772  				}
   773  			case string:
   774  				if err := d.literalStore([]byte(qv), subv, true); err != nil {
   775  					return err
   776  				}
   777  			default:
   778  				d.saveError(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal unquoted value into %v", subv.Type()))
   779  			}
   780  		} else {
   781  			if err := d.value(subv); err != nil {
   782  				return err
   783  			}
   784  		}
   785  
   786  		// Write value back to map;
   787  		// if using struct, subv points into struct already.
   788  		if v.Kind() == reflect.Map {
   789  			kt := v.Type().Key()
   790  			var kv reflect.Value
   791  			switch {
   792  			case kt.Kind() == reflect.String:
   793  				kv = reflect.ValueOf(key).Convert(kt)
   794  			case reflect.PtrTo(kt).Implements(textUnmarshalerType):
   795  				kv = reflect.New(v.Type().Key())
   796  				if err := d.literalStore(item, kv, true); err != nil {
   797  					return err
   798  				}
   799  				kv = kv.Elem()
   800  			default:
   801  				switch kt.Kind() {
   802  				case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
   803  					s := string(key)
   804  					n, err := strconv.ParseInt(s, 10, 64)
   805  					if err != nil || reflect.Zero(kt).OverflowInt(n) {
   806  						d.saveError(&UnmarshalTypeError{Value: "number " + s, Type: kt, Offset: int64(start + 1)})
   807  						return nil
   808  					}
   809  					kv = reflect.ValueOf(n).Convert(kt)
   810  				case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
   811  					s := string(key)
   812  					n, err := strconv.ParseUint(s, 10, 64)
   813  					if err != nil || reflect.Zero(kt).OverflowUint(n) {
   814  						d.saveError(&UnmarshalTypeError{Value: "number " + s, Type: kt, Offset: int64(start + 1)})
   815  						return nil
   816  					}
   817  					kv = reflect.ValueOf(n).Convert(kt)
   818  				default:
   819  					panic("json: Unexpected key type") // should never occur
   820  				}
   821  			}
   822  			v.SetMapIndex(kv, subv)
   823  		}
   824  
   825  		// Next token must be , or }.
   826  		if d.opcode == scanSkipSpace {
   827  			d.scanWhile(scanSkipSpace)
   828  		}
   829  		if d.opcode == scanEndObject {
   830  			break
   831  		}
   832  		if d.opcode != scanObjectValue {
   833  			return errPhase
   834  		}
   835  
   836  		d.errorContext = originalErrorContext
   837  	}
   838  	return nil
   839  }
   840  
   841  // convertNumber converts the number literal s to a float64 or a Number
   842  // depending on the setting of d.useNumber.
   843  func (d *decodeState) convertNumber(s string) (interface{}, error) {
   844  	if d.useNumber {
   845  		return Number(s), nil
   846  	}
   847  	f, err := strconv.ParseFloat(s, 64)
   848  	if err != nil {
   849  		return nil, &UnmarshalTypeError{Value: "number " + s, Type: reflect.TypeOf(0.0), Offset: int64(d.off)}
   850  	}
   851  	return f, nil
   852  }
   853  
   854  var numberType = reflect.TypeOf(Number(""))
   855  
   856  // literalStore decodes a literal stored in item into v.
   857  //
   858  // fromQuoted indicates whether this literal came from unwrapping a
   859  // string from the ",string" struct tag option. this is used only to
   860  // produce more helpful error messages.
   861  func (d *decodeState) literalStore(item []byte, v reflect.Value, fromQuoted bool) error {
   862  	// Check for unmarshaler.
   863  	if len(item) == 0 {
   864  		//Empty string given
   865  		d.saveError(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type()))
   866  		return nil
   867  	}
   868  	isNull := item[0] == 'n' // null
   869  	u, ut, pv := indirect(v, isNull)
   870  	if u != nil {
   871  		return u.UnmarshalJSON(item)
   872  	}
   873  	if ut != nil {
   874  		if item[0] != '"' {
   875  			if fromQuoted {
   876  				d.saveError(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type()))
   877  			} else {
   878  				var val string
   879  				switch item[0] {
   880  				case 'n':
   881  					val = "null"
   882  				case 't', 'f':
   883  					val = "bool"
   884  				default:
   885  					val = "number"
   886  				}
   887  				d.saveError(&UnmarshalTypeError{Value: val, Type: v.Type(), Offset: int64(d.readIndex())})
   888  			}
   889  			return nil
   890  		}
   891  		s, ok := unquoteBytes(item)
   892  		if !ok {
   893  			if fromQuoted {
   894  				return fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type())
   895  			}
   896  			return errPhase
   897  		}
   898  		return ut.UnmarshalText(s)
   899  	}
   900  
   901  	v = pv
   902  
   903  	switch c := item[0]; c {
   904  	case 'n': // null
   905  		// The main parser checks that only true and false can reach here,
   906  		// but if this was a quoted string input, it could be anything.
   907  		if fromQuoted && string(item) != "null" {
   908  			d.saveError(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type()))
   909  			break
   910  		}
   911  		switch v.Kind() {
   912  		case reflect.Interface, reflect.Ptr, reflect.Map, reflect.Slice:
   913  			v.Set(reflect.Zero(v.Type()))
   914  			// otherwise, ignore null for primitives/string
   915  		}
   916  	case 't', 'f': // true, false
   917  		value := item[0] == 't'
   918  		// The main parser checks that only true and false can reach here,
   919  		// but if this was a quoted string input, it could be anything.
   920  		if fromQuoted && string(item) != "true" && string(item) != "false" {
   921  			d.saveError(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type()))
   922  			break
   923  		}
   924  		switch v.Kind() {
   925  		default:
   926  			if fromQuoted {
   927  				d.saveError(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type()))
   928  			} else {
   929  				d.saveError(&UnmarshalTypeError{Value: "bool", Type: v.Type(), Offset: int64(d.readIndex())})
   930  			}
   931  		case reflect.Bool:
   932  			v.SetBool(value)
   933  		case reflect.Interface:
   934  			if v.NumMethod() == 0 {
   935  				v.Set(reflect.ValueOf(value))
   936  			} else {
   937  				d.saveError(&UnmarshalTypeError{Value: "bool", Type: v.Type(), Offset: int64(d.readIndex())})
   938  			}
   939  		}
   940  
   941  	case '"': // string
   942  		s, ok := unquoteBytes(item)
   943  		if !ok {
   944  			if fromQuoted {
   945  				return fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type())
   946  			}
   947  			return errPhase
   948  		}
   949  		switch v.Kind() {
   950  		default:
   951  			d.saveError(&UnmarshalTypeError{Value: "string", Type: v.Type(), Offset: int64(d.readIndex())})
   952  		case reflect.Slice:
   953  			if v.Type().Elem().Kind() != reflect.Uint8 {
   954  				d.saveError(&UnmarshalTypeError{Value: "string", Type: v.Type(), Offset: int64(d.readIndex())})
   955  				break
   956  			}
   957  			b := make([]byte, base64.StdEncoding.DecodedLen(len(s)))
   958  			n, err := base64.StdEncoding.Decode(b, s)
   959  			if err != nil {
   960  				d.saveError(err)
   961  				break
   962  			}
   963  			v.SetBytes(b[:n])
   964  		case reflect.String:
   965  			v.SetString(string(s))
   966  		case reflect.Interface:
   967  			if v.NumMethod() == 0 {
   968  				v.Set(reflect.ValueOf(string(s)))
   969  			} else {
   970  				d.saveError(&UnmarshalTypeError{Value: "string", Type: v.Type(), Offset: int64(d.readIndex())})
   971  			}
   972  		}
   973  
   974  	default: // number
   975  		if c != '-' && (c < '0' || c > '9') {
   976  			if fromQuoted {
   977  				return fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type())
   978  			}
   979  			return errPhase
   980  		}
   981  		s := string(item)
   982  		switch v.Kind() {
   983  		default:
   984  			if v.Kind() == reflect.String && v.Type() == numberType {
   985  				v.SetString(s)
   986  				if !isValidNumber(s) {
   987  					return fmt.Errorf("json: invalid number literal, trying to unmarshal %q into Number", item)
   988  				}
   989  				break
   990  			}
   991  			if fromQuoted {
   992  				return fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type())
   993  			}
   994  			d.saveError(&UnmarshalTypeError{Value: "number", Type: v.Type(), Offset: int64(d.readIndex())})
   995  		case reflect.Interface:
   996  			n, err := d.convertNumber(s)
   997  			if err != nil {
   998  				d.saveError(err)
   999  				break
  1000  			}
  1001  			if v.NumMethod() != 0 {
  1002  				d.saveError(&UnmarshalTypeError{Value: "number", Type: v.Type(), Offset: int64(d.readIndex())})
  1003  				break
  1004  			}
  1005  			v.Set(reflect.ValueOf(n))
  1006  
  1007  		case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  1008  			n, err := strconv.ParseInt(s, 10, 64)
  1009  			if err != nil || v.OverflowInt(n) {
  1010  				d.saveError(&UnmarshalTypeError{Value: "number " + s, Type: v.Type(), Offset: int64(d.readIndex())})
  1011  				break
  1012  			}
  1013  			v.SetInt(n)
  1014  
  1015  		case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
  1016  			n, err := strconv.ParseUint(s, 10, 64)
  1017  			if err != nil || v.OverflowUint(n) {
  1018  				d.saveError(&UnmarshalTypeError{Value: "number " + s, Type: v.Type(), Offset: int64(d.readIndex())})
  1019  				break
  1020  			}
  1021  			v.SetUint(n)
  1022  
  1023  		case reflect.Float32, reflect.Float64:
  1024  			n, err := strconv.ParseFloat(s, v.Type().Bits())
  1025  			if err != nil || v.OverflowFloat(n) {
  1026  				d.saveError(&UnmarshalTypeError{Value: "number " + s, Type: v.Type(), Offset: int64(d.readIndex())})
  1027  				break
  1028  			}
  1029  			v.SetFloat(n)
  1030  		}
  1031  	}
  1032  	return nil
  1033  }
  1034  
  1035  // The xxxInterface routines build up a value to be stored
  1036  // in an empty interface. They are not strictly necessary,
  1037  // but they avoid the weight of reflection in this common case.
  1038  
  1039  // valueInterface is like value but returns interface{}
  1040  func (d *decodeState) valueInterface() (val interface{}, err error) {
  1041  	switch d.opcode {
  1042  	default:
  1043  		err = errPhase
  1044  	case scanBeginArray:
  1045  		val, err = d.arrayInterface()
  1046  		d.scanNext()
  1047  	case scanBeginObject:
  1048  		val, err = d.objectInterface()
  1049  		d.scanNext()
  1050  	case scanBeginLiteral:
  1051  		val, err = d.literalInterface()
  1052  	}
  1053  	return
  1054  }
  1055  
  1056  // arrayInterface is like array but returns []interface{}.
  1057  func (d *decodeState) arrayInterface() ([]interface{}, error) {
  1058  	var v = make([]interface{}, 0)
  1059  	for {
  1060  		// Look ahead for ] - can only happen on first iteration.
  1061  		d.scanWhile(scanSkipSpace)
  1062  		if d.opcode == scanEndArray {
  1063  			break
  1064  		}
  1065  
  1066  		vi, err := d.valueInterface()
  1067  		if err != nil {
  1068  			return nil, err
  1069  		}
  1070  		v = append(v, vi)
  1071  
  1072  		// Next token must be , or ].
  1073  		if d.opcode == scanSkipSpace {
  1074  			d.scanWhile(scanSkipSpace)
  1075  		}
  1076  		if d.opcode == scanEndArray {
  1077  			break
  1078  		}
  1079  		if d.opcode != scanArrayValue {
  1080  			return nil, errPhase
  1081  		}
  1082  	}
  1083  	return v, nil
  1084  }
  1085  
  1086  // objectInterface is like object but returns map[string]interface{}.
  1087  func (d *decodeState) objectInterface() (map[string]interface{}, error) {
  1088  	m := make(map[string]interface{})
  1089  	for {
  1090  		// Read opening " of string key or closing }.
  1091  		d.scanWhile(scanSkipSpace)
  1092  		if d.opcode == scanEndObject {
  1093  			// closing } - can only happen on first iteration.
  1094  			break
  1095  		}
  1096  		if d.opcode != scanBeginLiteral {
  1097  			return nil, errPhase
  1098  		}
  1099  
  1100  		// Read string key.
  1101  		start := d.readIndex()
  1102  		d.scanWhile(scanContinue)
  1103  		item := d.data[start:d.readIndex()]
  1104  		key, ok := unquote(item)
  1105  		if !ok {
  1106  			return nil, errPhase
  1107  		}
  1108  
  1109  		// Read : before value.
  1110  		if d.opcode == scanSkipSpace {
  1111  			d.scanWhile(scanSkipSpace)
  1112  		}
  1113  		if d.opcode != scanObjectKey {
  1114  			return nil, errPhase
  1115  		}
  1116  		d.scanWhile(scanSkipSpace)
  1117  
  1118  		// Read value.
  1119  		vi, err := d.valueInterface()
  1120  		if err != nil {
  1121  			return nil, err
  1122  		}
  1123  		m[key] = vi
  1124  
  1125  		// Next token must be , or }.
  1126  		if d.opcode == scanSkipSpace {
  1127  			d.scanWhile(scanSkipSpace)
  1128  		}
  1129  		if d.opcode == scanEndObject {
  1130  			break
  1131  		}
  1132  		if d.opcode != scanObjectValue {
  1133  			return nil, errPhase
  1134  		}
  1135  	}
  1136  	return m, nil
  1137  }
  1138  
  1139  // literalInterface consumes and returns a literal from d.data[d.off-1:] and
  1140  // it reads the following byte ahead. The first byte of the literal has been
  1141  // read already (that's how the caller knows it's a literal).
  1142  func (d *decodeState) literalInterface() (interface{}, error) {
  1143  	// All bytes inside literal return scanContinue op code.
  1144  	start := d.readIndex()
  1145  	d.scanWhile(scanContinue)
  1146  
  1147  	item := d.data[start:d.readIndex()]
  1148  
  1149  	switch c := item[0]; c {
  1150  	case 'n': // null
  1151  		return nil, nil
  1152  
  1153  	case 't', 'f': // true, false
  1154  		return c == 't', nil
  1155  
  1156  	case '"': // string
  1157  		s, ok := unquote(item)
  1158  		if !ok {
  1159  			return nil, errPhase
  1160  		}
  1161  		return s, nil
  1162  
  1163  	default: // number
  1164  		if c != '-' && (c < '0' || c > '9') {
  1165  			return nil, errPhase
  1166  		}
  1167  		n, err := d.convertNumber(string(item))
  1168  		if err != nil {
  1169  			d.saveError(err)
  1170  		}
  1171  		return n, nil
  1172  	}
  1173  }
  1174  
  1175  // getu4 decodes \uXXXX from the beginning of s, returning the hex value,
  1176  // or it returns -1.
  1177  func getu4(s []byte) rune {
  1178  	if len(s) < 6 || s[0] != '\\' || s[1] != 'u' {
  1179  		return -1
  1180  	}
  1181  	var r rune
  1182  	for _, c := range s[2:6] {
  1183  		switch {
  1184  		case '0' <= c && c <= '9':
  1185  			c = c - '0'
  1186  		case 'a' <= c && c <= 'f':
  1187  			c = c - 'a' + 10
  1188  		case 'A' <= c && c <= 'F':
  1189  			c = c - 'A' + 10
  1190  		default:
  1191  			return -1
  1192  		}
  1193  		r = r*16 + rune(c)
  1194  	}
  1195  	return r
  1196  }
  1197  
  1198  // unquote converts a quoted JSON string literal s into an actual string t.
  1199  // The rules are different than for Go, so cannot use strconv.Unquote.
  1200  func unquote(s []byte) (t string, ok bool) {
  1201  	s, ok = unquoteBytes(s)
  1202  	t = string(s)
  1203  	return
  1204  }
  1205  
  1206  func unquoteBytes(s []byte) (t []byte, ok bool) {
  1207  	if len(s) < 2 || s[0] != '"' || s[len(s)-1] != '"' {
  1208  		return
  1209  	}
  1210  	s = s[1 : len(s)-1]
  1211  
  1212  	// Check for unusual characters. If there are none,
  1213  	// then no unquoting is needed, so return a slice of the
  1214  	// original bytes.
  1215  	r := 0
  1216  	for r < len(s) {
  1217  		c := s[r]
  1218  		if c == '\\' || c == '"' || c < ' ' {
  1219  			break
  1220  		}
  1221  		if c < utf8.RuneSelf {
  1222  			r++
  1223  			continue
  1224  		}
  1225  		rr, size := utf8.DecodeRune(s[r:])
  1226  		if rr == utf8.RuneError && size == 1 {
  1227  			break
  1228  		}
  1229  		r += size
  1230  	}
  1231  	if r == len(s) {
  1232  		return s, true
  1233  	}
  1234  
  1235  	b := make([]byte, len(s)+2*utf8.UTFMax)
  1236  	w := copy(b, s[0:r])
  1237  	for r < len(s) {
  1238  		// Out of room? Can only happen if s is full of
  1239  		// malformed UTF-8 and we're replacing each
  1240  		// byte with RuneError.
  1241  		if w >= len(b)-2*utf8.UTFMax {
  1242  			nb := make([]byte, (len(b)+utf8.UTFMax)*2)
  1243  			copy(nb, b[0:w])
  1244  			b = nb
  1245  		}
  1246  		switch c := s[r]; {
  1247  		case c == '\\':
  1248  			r++
  1249  			if r >= len(s) {
  1250  				return
  1251  			}
  1252  			switch s[r] {
  1253  			default:
  1254  				return
  1255  			case '"', '\\', '/', '\'':
  1256  				b[w] = s[r]
  1257  				r++
  1258  				w++
  1259  			case 'b':
  1260  				b[w] = '\b'
  1261  				r++
  1262  				w++
  1263  			case 'f':
  1264  				b[w] = '\f'
  1265  				r++
  1266  				w++
  1267  			case 'n':
  1268  				b[w] = '\n'
  1269  				r++
  1270  				w++
  1271  			case 'r':
  1272  				b[w] = '\r'
  1273  				r++
  1274  				w++
  1275  			case 't':
  1276  				b[w] = '\t'
  1277  				r++
  1278  				w++
  1279  			case 'u':
  1280  				r--
  1281  				rr := getu4(s[r:])
  1282  				if rr < 0 {
  1283  					return
  1284  				}
  1285  				r += 6
  1286  				if utf16.IsSurrogate(rr) {
  1287  					rr1 := getu4(s[r:])
  1288  					if dec := utf16.DecodeRune(rr, rr1); dec != unicode.ReplacementChar {
  1289  						// A valid pair; consume.
  1290  						r += 6
  1291  						w += utf8.EncodeRune(b[w:], dec)
  1292  						break
  1293  					}
  1294  					// Invalid surrogate; fall back to replacement rune.
  1295  					rr = unicode.ReplacementChar
  1296  				}
  1297  				w += utf8.EncodeRune(b[w:], rr)
  1298  			}
  1299  
  1300  		// Quote, control characters are invalid.
  1301  		case c == '"', c < ' ':
  1302  			return
  1303  
  1304  		// ASCII
  1305  		case c < utf8.RuneSelf:
  1306  			b[w] = c
  1307  			r++
  1308  			w++
  1309  
  1310  		// Coerce to well-formed UTF-8.
  1311  		default:
  1312  			rr, size := utf8.DecodeRune(s[r:])
  1313  			r += size
  1314  			w += utf8.EncodeRune(b[w:], rr)
  1315  		}
  1316  	}
  1317  	return b[0:w], true
  1318  }
  1319  

View as plain text