1 // Copyright 2010 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
5 // Represents JSON data structure using native Go types: booleans, floats,
6 // strings, arrays, and maps.
24 // Unmarshal parses the JSON-encoded data and stores the result
25 // in the value pointed to by v. If v is nil or not a pointer,
26 // Unmarshal returns an InvalidUnmarshalError.
28 // Unmarshal uses the inverse of the encodings that
29 // Marshal uses, allocating maps, slices, and pointers as necessary,
30 // with the following additional rules:
32 // To unmarshal JSON into a pointer, Unmarshal first handles the case of
33 // the JSON being the JSON literal null. In that case, Unmarshal sets
34 // the pointer to nil. Otherwise, Unmarshal unmarshals the JSON into
35 // the value pointed at by the pointer. If the pointer is nil, Unmarshal
36 // allocates a new value for it to point to.
38 // To unmarshal JSON into a value implementing the Unmarshaler interface,
39 // Unmarshal calls that value's UnmarshalJSON method, including
40 // when the input is a JSON null.
41 // Otherwise, if the value implements encoding.TextUnmarshaler
42 // and the input is a JSON quoted string, Unmarshal calls that value's
43 // UnmarshalText method with the unquoted form of the string.
45 // To unmarshal JSON into a struct, Unmarshal matches incoming object
46 // keys to the keys used by Marshal (either the struct field name or its tag),
47 // preferring an exact match but also accepting a case-insensitive match. By
48 // default, object keys which don't have a corresponding struct field are
49 // ignored (see Decoder.DisallowUnknownFields for an alternative).
51 // To unmarshal JSON into an interface value,
52 // Unmarshal stores one of these in the interface value:
54 // bool, for JSON booleans
55 // float64, for JSON numbers
56 // string, for JSON strings
57 // []interface{}, for JSON arrays
58 // map[string]interface{}, for JSON objects
61 // To unmarshal a JSON array into a slice, Unmarshal resets the slice length
62 // to zero and then appends each element to the slice.
63 // As a special case, to unmarshal an empty JSON array into a slice,
64 // Unmarshal replaces the slice with a new empty slice.
66 // To unmarshal a JSON array into a Go array, Unmarshal decodes
67 // JSON array elements into corresponding Go array elements.
68 // If the Go array is smaller than the JSON array,
69 // the additional JSON array elements are discarded.
70 // If the JSON array is smaller than the Go array,
71 // the additional Go array elements are set to zero values.
73 // To unmarshal a JSON object into a map, Unmarshal first establishes a map to
74 // use. If the map is nil, Unmarshal allocates a new map. Otherwise Unmarshal
75 // reuses the existing map, keeping existing entries. Unmarshal then stores
76 // key-value pairs from the JSON object into the map. The map's key type must
77 // either be a string, an integer, or implement encoding.TextUnmarshaler.
79 // If a JSON value is not appropriate for a given target type,
80 // or if a JSON number overflows the target type, Unmarshal
81 // skips that field and completes the unmarshaling as best it can.
82 // If no more serious errors are encountered, Unmarshal returns
83 // an UnmarshalTypeError describing the earliest such error. In any
84 // case, it's not guaranteed that all the remaining fields following
85 // the problematic one will be unmarshaled into the target object.
87 // The JSON null value unmarshals into an interface, map, pointer, or slice
88 // by setting that Go value to nil. Because null is often used in JSON to mean
89 // ``not present,'' unmarshaling a JSON null into any other Go type has no effect
90 // on the value and produces no error.
92 // When unmarshaling quoted strings, invalid UTF-8 or
93 // invalid UTF-16 surrogate pairs are not treated as an error.
94 // Instead, they are replaced by the Unicode replacement
97 func Unmarshal(data
[]byte, v
interface{}) error
{
98 // Check for well-formedness.
99 // Avoids filling out half a data structure
100 // before discovering a JSON syntax error.
102 err
:= checkValid(data
, &d
.scan
)
108 return d
.unmarshal(v
)
111 // Unmarshaler is the interface implemented by types
112 // that can unmarshal a JSON description of themselves.
113 // The input can be assumed to be a valid encoding of
114 // a JSON value. UnmarshalJSON must copy the JSON data
115 // if it wishes to retain the data after returning.
117 // By convention, to approximate the behavior of Unmarshal itself,
118 // Unmarshalers implement UnmarshalJSON([]byte("null")) as a no-op.
119 type Unmarshaler
interface {
120 UnmarshalJSON([]byte) error
123 // An UnmarshalTypeError describes a JSON value that was
124 // not appropriate for a value of a specific Go type.
125 type UnmarshalTypeError
struct {
126 Value
string // description of JSON value - "bool", "array", "number -5"
127 Type reflect
.Type
// type of Go value it could not be assigned to
128 Offset
int64 // error occurred after reading Offset bytes
129 Struct
string // name of the struct type containing the field
130 Field
string // name of the field holding the Go value
133 func (e
*UnmarshalTypeError
) Error() string {
134 if e
.Struct
!= "" || e
.Field
!= "" {
135 return "json: cannot unmarshal " + e
.Value
+ " into Go struct field " + e
.Struct
+ "." + e
.Field
+ " of type " + e
.Type
.String()
137 return "json: cannot unmarshal " + e
.Value
+ " into Go value of type " + e
.Type
.String()
140 // An UnmarshalFieldError describes a JSON object key that
141 // led to an unexported (and therefore unwritable) struct field.
143 // Deprecated: No longer used; kept for compatibility.
144 type UnmarshalFieldError
struct {
147 Field reflect
.StructField
150 func (e
*UnmarshalFieldError
) Error() string {
151 return "json: cannot unmarshal object key " + strconv
.Quote(e
.Key
) + " into unexported field " + e
.Field
.Name
+ " of type " + e
.Type
.String()
154 // An InvalidUnmarshalError describes an invalid argument passed to Unmarshal.
155 // (The argument to Unmarshal must be a non-nil pointer.)
156 type InvalidUnmarshalError
struct {
160 func (e
*InvalidUnmarshalError
) Error() string {
162 return "json: Unmarshal(nil)"
165 if e
.Type
.Kind() != reflect
.Ptr
{
166 return "json: Unmarshal(non-pointer " + e
.Type
.String() + ")"
168 return "json: Unmarshal(nil " + e
.Type
.String() + ")"
171 func (d
*decodeState
) unmarshal(v
interface{}) (err error
) {
173 if r
:= recover(); r
!= nil {
174 if _
, ok
:= r
.(runtime
.Error
); ok
{
181 rv
:= reflect
.ValueOf(v
)
182 if rv
.Kind() != reflect
.Ptr || rv
.IsNil() {
183 return &InvalidUnmarshalError
{reflect
.TypeOf(v
)}
187 // We decode rv not rv.Elem because the Unmarshaler interface
188 // test must be applied at the top level of the value.
193 // A Number represents a JSON number literal.
196 // String returns the literal text of the number.
197 func (n Number
) String() string { return string(n
) }
199 // Float64 returns the number as a float64.
200 func (n Number
) Float64() (float64, error
) {
201 return strconv
.ParseFloat(string(n
), 64)
204 // Int64 returns the number as an int64.
205 func (n Number
) Int64() (int64, error
) {
206 return strconv
.ParseInt(string(n
), 10, 64)
209 // isValidNumber reports whether s is a valid JSON number literal.
210 func isValidNumber(s
string) bool {
211 // This function implements the JSON numbers grammar.
212 // See https://tools.ietf.org/html/rfc7159#section-6
213 // and http://json.org/number.gif
235 case '1' <= s
[0] && s
[0] <= '9':
237 for len(s
) > 0 && '0' <= s
[0] && s
[0] <= '9' {
242 // . followed by 1 or more digits.
243 if len(s
) >= 2 && s
[0] == '.' && '0' <= s
[1] && s
[1] <= '9' {
245 for len(s
) > 0 && '0' <= s
[0] && s
[0] <= '9' {
250 // e or E followed by an optional - or + and
252 if len(s
) >= 2 && (s
[0] == 'e' || s
[0] == 'E') {
254 if s
[0] == '+' || s
[0] == '-' {
260 for len(s
) > 0 && '0' <= s
[0] && s
[0] <= '9' {
265 // Make sure we are at the end.
269 // decodeState represents the state while decoding a JSON value.
270 type decodeState
struct {
272 off
int // read offset in data
274 nextscan scanner
// for calls to nextValue
275 errorContext
struct { // provides context for type errors
281 disallowUnknownFields
bool
284 // errPhase is used for errors that should not happen unless
285 // there is a bug in the JSON decoder or something is editing
286 // the data slice while the decoder executes.
287 var errPhase
= errors
.New("JSON decoder out of sync - data changing underfoot?")
289 func (d
*decodeState
) init(data
[]byte) *decodeState
{
293 d
.errorContext
.Struct
= ""
294 d
.errorContext
.Field
= ""
298 // error aborts the decoding by panicking with err.
299 func (d
*decodeState
) error(err error
) {
300 panic(d
.addErrorContext(err
))
303 // saveError saves the first err it is called with,
304 // for reporting at the end of the unmarshal.
305 func (d
*decodeState
) saveError(err error
) {
306 if d
.savedError
== nil {
307 d
.savedError
= d
.addErrorContext(err
)
311 // addErrorContext returns a new error enhanced with information from d.errorContext
312 func (d
*decodeState
) addErrorContext(err error
) error
{
313 if d
.errorContext
.Struct
!= "" || d
.errorContext
.Field
!= "" {
314 switch err
:= err
.(type) {
315 case *UnmarshalTypeError
:
316 err
.Struct
= d
.errorContext
.Struct
317 err
.Field
= d
.errorContext
.Field
324 // next cuts off and returns the next full JSON value in d.data[d.off:].
325 // The next value is known to be an object or array, not a literal.
326 func (d
*decodeState
) next() []byte {
328 item
, rest
, err
:= nextValue(d
.data
[d
.off
:], &d
.nextscan
)
332 d
.off
= len(d
.data
) - len(rest
)
334 // Our scanner has seen the opening brace/bracket
335 // and thinks we're still in the middle of the object.
336 // invent a closing brace/bracket to get it out.
338 d
.scan
.step(&d
.scan
, '}')
340 d
.scan
.step(&d
.scan
, ']')
346 // scanWhile processes bytes in d.data[d.off:] until it
347 // receives a scan code not equal to op.
348 // It updates d.off and returns the new scan code.
349 func (d
*decodeState
) scanWhile(op
int) int {
352 if d
.off
>= len(d
.data
) {
354 d
.off
= len(d
.data
) + 1 // mark processed EOF with len+1
358 newOp
= d
.scan
.step(&d
.scan
, c
)
367 // value decodes a JSON value from d.data[d.off:] into the value.
368 // it updates d.off to point past the decoded value.
369 func (d
*decodeState
) value(v reflect
.Value
) {
371 _
, rest
, err
:= nextValue(d
.data
[d
.off
:], &d
.nextscan
)
375 d
.off
= len(d
.data
) - len(rest
)
377 // d.scan thinks we're still at the beginning of the item.
378 // Feed in an empty string - the shortest, simplest value -
379 // so that it knows we got to the end of the value.
383 d
.scan
.step
= stateBeginValue
385 d
.scan
.step(&d
.scan
, '"')
386 d
.scan
.step(&d
.scan
, '"')
388 n
:= len(d
.scan
.parseState
)
389 if n
> 0 && d
.scan
.parseState
[n
-1] == parseObjectKey
{
390 // d.scan thinks we just read an object key; finish the object
391 d
.scan
.step(&d
.scan
, ':')
392 d
.scan
.step(&d
.scan
, '"')
393 d
.scan
.step(&d
.scan
, '"')
394 d
.scan
.step(&d
.scan
, '}')
400 switch op
:= d
.scanWhile(scanSkipSpace
); op
{
407 case scanBeginObject
:
410 case scanBeginLiteral
:
415 type unquotedValue
struct{}
417 // valueQuoted is like value but decodes a
418 // quoted string literal or literal null into an interface value.
419 // If it finds anything other than a quoted string literal or null,
420 // valueQuoted returns unquotedValue{}.
421 func (d
*decodeState
) valueQuoted() interface{} {
422 switch op
:= d
.scanWhile(scanSkipSpace
); op
{
427 d
.array(reflect
.Value
{})
429 case scanBeginObject
:
430 d
.object(reflect
.Value
{})
432 case scanBeginLiteral
:
433 switch v
:= d
.literalInterface().(type) {
438 return unquotedValue
{}
441 // indirect walks down v allocating pointers as needed,
442 // until it gets to a non-pointer.
443 // if it encounters an Unmarshaler, indirect stops and returns that.
444 // if decodingNull is true, indirect stops at the last pointer so it can be set to nil.
445 func (d
*decodeState
) indirect(v reflect
.Value
, decodingNull
bool) (Unmarshaler
, encoding
.TextUnmarshaler
, reflect
.Value
) {
446 // Issue #24153 indicates that it is generally not a guaranteed property
447 // that you may round-trip a reflect.Value by calling Value.Addr().Elem()
448 // and expect the value to still be settable for values derived from
449 // unexported embedded struct fields.
451 // The logic below effectively does this when it first addresses the value
452 // (to satisfy possible pointer methods) and continues to dereference
453 // subsequent pointers as necessary.
455 // After the first round-trip, we set v back to the original value to
456 // preserve the original RW flags contained in reflect.Value.
460 // If v is a named type and is addressable,
461 // start with its address, so that if the type has pointer methods,
463 if v
.Kind() != reflect
.Ptr
&& v
.Type().Name() != "" && v
.CanAddr() {
468 // Load value from interface, but only if the result will be
469 // usefully addressable.
470 if v
.Kind() == reflect
.Interface
&& !v
.IsNil() {
472 if e
.Kind() == reflect
.Ptr
&& !e
.IsNil() && (!decodingNull || e
.Elem().Kind() == reflect
.Ptr
) {
479 if v
.Kind() != reflect
.Ptr
{
483 if v
.Elem().Kind() != reflect
.Ptr
&& decodingNull
&& v
.CanSet() {
487 v
.Set(reflect
.New(v
.Type().Elem()))
489 if v
.Type().NumMethod() > 0 {
490 if u
, ok
:= v
.Interface().(Unmarshaler
); ok
{
491 return u
, nil, reflect
.Value
{}
494 if u
, ok
:= v
.Interface().(encoding
.TextUnmarshaler
); ok
{
495 return nil, u
, reflect
.Value
{}
501 v
= v0
// restore original value after round-trip Value.Addr().Elem()
510 // array consumes an array from d.data[d.off-1:], decoding into the value v.
511 // the first byte of the array ('[') has been read already.
512 func (d
*decodeState
) array(v reflect
.Value
) {
513 // Check for unmarshaler.
514 u
, ut
, pv
:= d
.indirect(v
, false)
517 err
:= u
.UnmarshalJSON(d
.next())
524 d
.saveError(&UnmarshalTypeError
{Value
: "array", Type
: v
.Type(), Offset
: int64(d
.off
)})
532 // Check type of target.
534 case reflect
.Interface
:
535 if v
.NumMethod() == 0 {
536 // Decoding into nil interface? Switch to non-reflect code.
537 v
.Set(reflect
.ValueOf(d
.arrayInterface()))
540 // Otherwise it's invalid.
543 d
.saveError(&UnmarshalTypeError
{Value
: "array", Type
: v
.Type(), Offset
: int64(d
.off
)})
554 // Look ahead for ] - can only happen on first iteration.
555 op
:= d
.scanWhile(scanSkipSpace
)
556 if op
== scanEndArray
{
560 // Back up so d.value can have the byte we just read.
564 // Get element of array, growing if necessary.
565 if v
.Kind() == reflect
.Slice
{
566 // Grow slice if necessary
568 newcap
:= v
.Cap() + v
.Cap()/2
572 newv
:= reflect
.MakeSlice(v
.Type(), v
.Len(), newcap
)
573 reflect
.Copy(newv
, v
)
582 // Decode into element.
585 // Ran out of fixed array: skip.
586 d
.value(reflect
.Value
{})
590 // Next token must be , or ].
591 op
= d
.scanWhile(scanSkipSpace
)
592 if op
== scanEndArray
{
595 if op
!= scanArrayValue
{
601 if v
.Kind() == reflect
.Array
{
602 // Array. Zero the rest.
603 z
:= reflect
.Zero(v
.Type().Elem())
604 for ; i
< v
.Len(); i
++ {
611 if i
== 0 && v
.Kind() == reflect
.Slice
{
612 v
.Set(reflect
.MakeSlice(v
.Type(), 0, 0))
616 var nullLiteral
= []byte("null")
617 var textUnmarshalerType
= reflect
.TypeOf(new(encoding
.TextUnmarshaler
)).Elem()
619 // object consumes an object from d.data[d.off-1:], decoding into the value v.
620 // the first byte ('{') of the object has been read already.
621 func (d
*decodeState
) object(v reflect
.Value
) {
622 // Check for unmarshaler.
623 u
, ut
, pv
:= d
.indirect(v
, false)
626 err
:= u
.UnmarshalJSON(d
.next())
633 d
.saveError(&UnmarshalTypeError
{Value
: "object", Type
: v
.Type(), Offset
: int64(d
.off
)})
635 d
.next() // skip over { } in input
640 // Decoding into nil interface? Switch to non-reflect code.
641 if v
.Kind() == reflect
.Interface
&& v
.NumMethod() == 0 {
642 v
.Set(reflect
.ValueOf(d
.objectInterface()))
646 // Check type of target:
648 // map[T1]T2 where T1 is string, an integer type,
649 // or an encoding.TextUnmarshaler
652 // Map key must either have string kind, have an integer kind,
653 // or be an encoding.TextUnmarshaler.
655 switch t
.Key().Kind() {
657 reflect
.Int
, reflect
.Int8
, reflect
.Int16
, reflect
.Int32
, reflect
.Int64
,
658 reflect
.Uint
, reflect
.Uint8
, reflect
.Uint16
, reflect
.Uint32
, reflect
.Uint64
, reflect
.Uintptr
:
660 if !reflect
.PtrTo(t
.Key()).Implements(textUnmarshalerType
) {
661 d
.saveError(&UnmarshalTypeError
{Value
: "object", Type
: v
.Type(), Offset
: int64(d
.off
)})
663 d
.next() // skip over { } in input
668 v
.Set(reflect
.MakeMap(t
))
673 d
.saveError(&UnmarshalTypeError
{Value
: "object", Type
: v
.Type(), Offset
: int64(d
.off
)})
675 d
.next() // skip over { } in input
679 var mapElem reflect
.Value
682 // Read opening " of string key or closing }.
683 op
:= d
.scanWhile(scanSkipSpace
)
684 if op
== scanEndObject
{
685 // closing } - can only happen on first iteration.
688 if op
!= scanBeginLiteral
{
694 op
= d
.scanWhile(scanContinue
)
695 item
:= d
.data
[start
: d
.off
-1]
696 key
, ok
:= unquoteBytes(item
)
701 // Figure out field corresponding to key.
702 var subv reflect
.Value
703 destring
:= false // whether the value is wrapped in a string to be decoded first
705 if v
.Kind() == reflect
.Map
{
706 elemType
:= v
.Type().Elem()
707 if !mapElem
.IsValid() {
708 mapElem
= reflect
.New(elemType
).Elem()
710 mapElem
.Set(reflect
.Zero(elemType
))
715 fields
:= cachedTypeFields(v
.Type())
716 for i
:= range fields
{
718 if bytes
.Equal(ff
.nameBytes
, key
) {
722 if f
== nil && ff
.equalFold(ff
.nameBytes
, key
) {
729 for _
, i
:= range f
.index
{
730 if subv
.Kind() == reflect
.Ptr
{
732 // If a struct embeds a pointer to an unexported type,
733 // it is not possible to set a newly allocated value
734 // since the field is unexported.
736 // See https://golang.org/issue/21357
738 d
.saveError(fmt
.Errorf("json: cannot set embedded pointer to unexported struct: %v", subv
.Type().Elem()))
739 // Invalidate subv to ensure d.value(subv) skips over
740 // the JSON value without assigning it to subv.
741 subv
= reflect
.Value
{}
745 subv
.Set(reflect
.New(subv
.Type().Elem()))
751 d
.errorContext
.Field
= f
.name
752 d
.errorContext
.Struct
= v
.Type().Name()
753 } else if d
.disallowUnknownFields
{
754 d
.saveError(fmt
.Errorf("json: unknown field %q", key
))
758 // Read : before value.
759 if op
== scanSkipSpace
{
760 op
= d
.scanWhile(scanSkipSpace
)
762 if op
!= scanObjectKey
{
767 switch qv
:= d
.valueQuoted().(type) {
769 d
.literalStore(nullLiteral
, subv
, false)
771 d
.literalStore([]byte(qv
), subv
, true)
773 d
.saveError(fmt
.Errorf("json: invalid use of ,string struct tag, trying to unmarshal unquoted value into %v", subv
.Type()))
779 // Write value back to map;
780 // if using struct, subv points into struct already.
781 if v
.Kind() == reflect
.Map
{
785 case kt
.Kind() == reflect
.String
:
786 kv
= reflect
.ValueOf(key
).Convert(kt
)
787 case reflect
.PtrTo(kt
).Implements(textUnmarshalerType
):
788 kv
= reflect
.New(v
.Type().Key())
789 d
.literalStore(item
, kv
, true)
793 case reflect
.Int
, reflect
.Int8
, reflect
.Int16
, reflect
.Int32
, reflect
.Int64
:
795 n
, err
:= strconv
.ParseInt(s
, 10, 64)
796 if err
!= nil || reflect
.Zero(kt
).OverflowInt(n
) {
797 d
.saveError(&UnmarshalTypeError
{Value
: "number " + s
, Type
: kt
, Offset
: int64(start
+ 1)})
800 kv
= reflect
.ValueOf(n
).Convert(kt
)
801 case reflect
.Uint
, reflect
.Uint8
, reflect
.Uint16
, reflect
.Uint32
, reflect
.Uint64
, reflect
.Uintptr
:
803 n
, err
:= strconv
.ParseUint(s
, 10, 64)
804 if err
!= nil || reflect
.Zero(kt
).OverflowUint(n
) {
805 d
.saveError(&UnmarshalTypeError
{Value
: "number " + s
, Type
: kt
, Offset
: int64(start
+ 1)})
808 kv
= reflect
.ValueOf(n
).Convert(kt
)
810 panic("json: Unexpected key type") // should never occur
813 v
.SetMapIndex(kv
, subv
)
816 // Next token must be , or }.
817 op
= d
.scanWhile(scanSkipSpace
)
818 if op
== scanEndObject
{
821 if op
!= scanObjectValue
{
825 d
.errorContext
.Struct
= ""
826 d
.errorContext
.Field
= ""
830 // literal consumes a literal from d.data[d.off-1:], decoding into the value v.
831 // The first byte of the literal has been read already
832 // (that's how the caller knows it's a literal).
833 func (d
*decodeState
) literal(v reflect
.Value
) {
834 // All bytes inside literal return scanContinue op code.
836 op
:= d
.scanWhile(scanContinue
)
838 // Scan read one byte too far; back up.
842 d
.literalStore(d
.data
[start
:d
.off
], v
, false)
845 // convertNumber converts the number literal s to a float64 or a Number
846 // depending on the setting of d.useNumber.
847 func (d
*decodeState
) convertNumber(s
string) (interface{}, error
) {
849 return Number(s
), nil
851 f
, err
:= strconv
.ParseFloat(s
, 64)
853 return nil, &UnmarshalTypeError
{Value
: "number " + s
, Type
: reflect
.TypeOf(0.0), Offset
: int64(d
.off
)}
858 var numberType
= reflect
.TypeOf(Number(""))
860 // literalStore decodes a literal stored in item into v.
862 // fromQuoted indicates whether this literal came from unwrapping a
863 // string from the ",string" struct tag option. this is used only to
864 // produce more helpful error messages.
865 func (d
*decodeState
) literalStore(item
[]byte, v reflect
.Value
, fromQuoted
bool) {
866 // Check for unmarshaler.
869 d
.saveError(fmt
.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item
, v
.Type()))
872 isNull
:= item
[0] == 'n' // null
873 u
, ut
, pv
:= d
.indirect(v
, isNull
)
875 err
:= u
.UnmarshalJSON(item
)
884 d
.saveError(fmt
.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item
, v
.Type()))
895 d
.saveError(&UnmarshalTypeError
{Value
: val
, Type
: v
.Type(), Offset
: int64(d
.off
)})
899 s
, ok
:= unquoteBytes(item
)
902 d
.error(fmt
.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item
, v
.Type()))
907 err
:= ut
.UnmarshalText(s
)
916 switch c
:= item
[0]; c
{
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
) != "null" {
921 d
.saveError(fmt
.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item
, v
.Type()))
925 case reflect
.Interface
, reflect
.Ptr
, reflect
.Map
, reflect
.Slice
:
926 v
.Set(reflect
.Zero(v
.Type()))
927 // otherwise, ignore null for primitives/string
929 case 't', 'f': // true, false
930 value
:= item
[0] == 't'
931 // The main parser checks that only true and false can reach here,
932 // but if this was a quoted string input, it could be anything.
933 if fromQuoted
&& string(item
) != "true" && string(item
) != "false" {
934 d
.saveError(fmt
.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item
, v
.Type()))
940 d
.saveError(fmt
.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item
, v
.Type()))
942 d
.saveError(&UnmarshalTypeError
{Value
: "bool", Type
: v
.Type(), Offset
: int64(d
.off
)})
946 case reflect
.Interface
:
947 if v
.NumMethod() == 0 {
948 v
.Set(reflect
.ValueOf(value
))
950 d
.saveError(&UnmarshalTypeError
{Value
: "bool", Type
: v
.Type(), Offset
: int64(d
.off
)})
955 s
, ok
:= unquoteBytes(item
)
958 d
.error(fmt
.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item
, v
.Type()))
965 d
.saveError(&UnmarshalTypeError
{Value
: "string", Type
: v
.Type(), Offset
: int64(d
.off
)})
967 if v
.Type().Elem().Kind() != reflect
.Uint8
{
968 d
.saveError(&UnmarshalTypeError
{Value
: "string", Type
: v
.Type(), Offset
: int64(d
.off
)})
971 b
:= make([]byte, base64
.StdEncoding
.DecodedLen(len(s
)))
972 n
, err
:= base64
.StdEncoding
.Decode(b
, s
)
979 v
.SetString(string(s
))
980 case reflect
.Interface
:
981 if v
.NumMethod() == 0 {
982 v
.Set(reflect
.ValueOf(string(s
)))
984 d
.saveError(&UnmarshalTypeError
{Value
: "string", Type
: v
.Type(), Offset
: int64(d
.off
)})
989 if c
!= '-' && (c
< '0' || c
> '9') {
991 d
.error(fmt
.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item
, v
.Type()))
999 if v
.Kind() == reflect
.String
&& v
.Type() == numberType
{
1001 if !isValidNumber(s
) {
1002 d
.error(fmt
.Errorf("json: invalid number literal, trying to unmarshal %q into Number", item
))
1007 d
.error(fmt
.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item
, v
.Type()))
1009 d
.error(&UnmarshalTypeError
{Value
: "number", Type
: v
.Type(), Offset
: int64(d
.off
)})
1011 case reflect
.Interface
:
1012 n
, err
:= d
.convertNumber(s
)
1017 if v
.NumMethod() != 0 {
1018 d
.saveError(&UnmarshalTypeError
{Value
: "number", Type
: v
.Type(), Offset
: int64(d
.off
)})
1021 v
.Set(reflect
.ValueOf(n
))
1023 case reflect
.Int
, reflect
.Int8
, reflect
.Int16
, reflect
.Int32
, reflect
.Int64
:
1024 n
, err
:= strconv
.ParseInt(s
, 10, 64)
1025 if err
!= nil || v
.OverflowInt(n
) {
1026 d
.saveError(&UnmarshalTypeError
{Value
: "number " + s
, Type
: v
.Type(), Offset
: int64(d
.off
)})
1031 case reflect
.Uint
, reflect
.Uint8
, reflect
.Uint16
, reflect
.Uint32
, reflect
.Uint64
, reflect
.Uintptr
:
1032 n
, err
:= strconv
.ParseUint(s
, 10, 64)
1033 if err
!= nil || v
.OverflowUint(n
) {
1034 d
.saveError(&UnmarshalTypeError
{Value
: "number " + s
, Type
: v
.Type(), Offset
: int64(d
.off
)})
1039 case reflect
.Float32
, reflect
.Float64
:
1040 n
, err
:= strconv
.ParseFloat(s
, v
.Type().Bits())
1041 if err
!= nil || v
.OverflowFloat(n
) {
1042 d
.saveError(&UnmarshalTypeError
{Value
: "number " + s
, Type
: v
.Type(), Offset
: int64(d
.off
)})
1050 // The xxxInterface routines build up a value to be stored
1051 // in an empty interface. They are not strictly necessary,
1052 // but they avoid the weight of reflection in this common case.
1054 // valueInterface is like value but returns interface{}
1055 func (d
*decodeState
) valueInterface() interface{} {
1056 switch d
.scanWhile(scanSkipSpace
) {
1059 panic("unreachable")
1060 case scanBeginArray
:
1061 return d
.arrayInterface()
1062 case scanBeginObject
:
1063 return d
.objectInterface()
1064 case scanBeginLiteral
:
1065 return d
.literalInterface()
1069 // arrayInterface is like array but returns []interface{}.
1070 func (d
*decodeState
) arrayInterface() []interface{} {
1071 var v
= make([]interface{}, 0)
1073 // Look ahead for ] - can only happen on first iteration.
1074 op
:= d
.scanWhile(scanSkipSpace
)
1075 if op
== scanEndArray
{
1079 // Back up so d.value can have the byte we just read.
1083 v
= append(v
, d
.valueInterface())
1085 // Next token must be , or ].
1086 op
= d
.scanWhile(scanSkipSpace
)
1087 if op
== scanEndArray
{
1090 if op
!= scanArrayValue
{
1097 // objectInterface is like object but returns map[string]interface{}.
1098 func (d
*decodeState
) objectInterface() map[string]interface{} {
1099 m
:= make(map[string]interface{})
1101 // Read opening " of string key or closing }.
1102 op
:= d
.scanWhile(scanSkipSpace
)
1103 if op
== scanEndObject
{
1104 // closing } - can only happen on first iteration.
1107 if op
!= scanBeginLiteral
{
1113 op
= d
.scanWhile(scanContinue
)
1114 item
:= d
.data
[start
: d
.off
-1]
1115 key
, ok
:= unquote(item
)
1120 // Read : before value.
1121 if op
== scanSkipSpace
{
1122 op
= d
.scanWhile(scanSkipSpace
)
1124 if op
!= scanObjectKey
{
1129 m
[key
] = d
.valueInterface()
1131 // Next token must be , or }.
1132 op
= d
.scanWhile(scanSkipSpace
)
1133 if op
== scanEndObject
{
1136 if op
!= scanObjectValue
{
1143 // literalInterface is like literal but returns an interface value.
1144 func (d
*decodeState
) literalInterface() interface{} {
1145 // All bytes inside literal return scanContinue op code.
1147 op
:= d
.scanWhile(scanContinue
)
1149 // Scan read one byte too far; back up.
1152 item
:= d
.data
[start
:d
.off
]
1154 switch c
:= item
[0]; c
{
1158 case 't', 'f': // true, false
1162 s
, ok
:= unquote(item
)
1169 if c
!= '-' && (c
< '0' || c
> '9') {
1172 n
, err
:= d
.convertNumber(string(item
))
1180 // getu4 decodes \uXXXX from the beginning of s, returning the hex value,
1181 // or it returns -1.
1182 func getu4(s
[]byte) rune
{
1183 if len(s
) < 6 || s
[0] != '\\' || s
[1] != 'u' {
1187 for _
, c
:= range s
[2:6] {
1189 case '0' <= c
&& c
<= '9':
1191 case 'a' <= c
&& c
<= 'f':
1193 case 'A' <= c
&& c
<= 'F':
1203 // unquote converts a quoted JSON string literal s into an actual string t.
1204 // The rules are different than for Go, so cannot use strconv.Unquote.
1205 func unquote(s
[]byte) (t
string, ok
bool) {
1206 s
, ok
= unquoteBytes(s
)
1211 func unquoteBytes(s
[]byte) (t
[]byte, ok
bool) {
1212 if len(s
) < 2 || s
[0] != '"' || s
[len(s
)-1] != '"' {
1217 // Check for unusual characters. If there are none,
1218 // then no unquoting is needed, so return a slice of the
1223 if c
== '\\' || c
== '"' || c
< ' ' {
1226 if c
< utf8
.RuneSelf
{
1230 rr
, size
:= utf8
.DecodeRune(s
[r
:])
1231 if rr
== utf8
.RuneError
&& size
== 1 {
1240 b
:= make([]byte, len(s
)+2*utf8
.UTFMax
)
1241 w
:= copy(b
, s
[0:r
])
1243 // Out of room? Can only happen if s is full of
1244 // malformed UTF-8 and we're replacing each
1245 // byte with RuneError.
1246 if w
>= len(b
)-2*utf8
.UTFMax
{
1247 nb
:= make([]byte, (len(b
)+utf8
.UTFMax
)*2)
1260 case '"', '\\', '/', '\'':
1291 if utf16
.IsSurrogate(rr
) {
1293 if dec
:= utf16
.DecodeRune(rr
, rr1
); dec
!= unicode
.ReplacementChar
{
1294 // A valid pair; consume.
1296 w
+= utf8
.EncodeRune(b
[w
:], dec
)
1299 // Invalid surrogate; fall back to replacement rune.
1300 rr
= unicode
.ReplacementChar
1302 w
+= utf8
.EncodeRune(b
[w
:], rr
)
1305 // Quote, control characters are invalid.
1306 case c
== '"', c
< ' ':
1310 case c
< utf8
.RuneSelf
:
1315 // Coerce to well-formed UTF-8.
1317 rr
, size
:= utf8
.DecodeRune(s
[r
:])
1319 w
+= utf8
.EncodeRune(b
[w
:], rr
)