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