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