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