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