decode.go 26 KB

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