You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1114 lines
27 KiB

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