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