decode.go 27 KB

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