| 1 |
// Copyright 2010 The Go Authors. All rights reserved. |
| 2 |
// Use of this source code is governed by a BSD-style |
| 3 |
// license that can be found in the LICENSE file. |
| 4 |
|
| 5 |
package json |
| 6 |
|
| 7 |
import ( |
| 8 |
"bytes" |
| 9 |
"errors" |
| 10 |
"io" |
| 11 |
) |
| 12 |
|
| 13 |
// A Decoder reads and decodes JSON objects from an input stream. |
| 14 |
type Decoder struct { |
| 15 |
r io.Reader |
| 16 |
buf []byte |
| 17 |
d decodeState |
| 18 |
scanp int // start of unread data in buf |
| 19 |
scan scanner |
| 20 |
err error |
| 21 |
|
| 22 |
tokenState int |
| 23 |
tokenStack []int |
| 24 |
} |
| 25 |
|
| 26 |
// NewDecoder returns a new decoder that reads from r. |
| 27 |
// |
| 28 |
// The decoder introduces its own buffering and may |
| 29 |
// read data from r beyond the JSON values requested. |
| 30 |
func NewDecoder(r io.Reader) *Decoder { |
| 31 |
return &Decoder{r: r} |
| 32 |
} |
| 33 |
|
| 34 |
// UseNumber causes the Decoder to unmarshal a number into an interface{} as a |
| 35 |
// Number instead of as a float64. |
| 36 |
func (dec *Decoder) UseNumber() { dec.d.useNumber = true } |
| 37 |
|
| 38 |
// Decode reads the next JSON-encoded value from its |
| 39 |
// input and stores it in the value pointed to by v. |
| 40 |
// |
| 41 |
// See the documentation for Unmarshal for details about |
| 42 |
// the conversion of JSON into a Go value. |
| 43 |
func (dec *Decoder) Decode(v interface{}) error { |
| 44 |
if dec.err != nil { |
| 45 |
return dec.err |
| 46 |
} |
| 47 |
|
| 48 |
if err := dec.tokenPrepareForDecode(); err != nil { |
| 49 |
return err |
| 50 |
} |
| 51 |
|
| 52 |
if !dec.tokenValueAllowed() { |
| 53 |
return &SyntaxError{msg: "not at beginning of value"} |
| 54 |
} |
| 55 |
|
| 56 |
// Read whole value into buffer. |
| 57 |
n, err := dec.readValue() |
| 58 |
if err != nil { |
| 59 |
return err |
| 60 |
} |
| 61 |
dec.d.init(dec.buf[dec.scanp : dec.scanp+n]) |
| 62 |
dec.scanp += n |
| 63 |
|
| 64 |
// Don't save err from unmarshal into dec.err: |
| 65 |
// the connection is still usable since we read a complete JSON |
| 66 |
// object from it before the error happened. |
| 67 |
err = dec.d.unmarshal(v) |
| 68 |
|
| 69 |
// fixup token streaming state |
| 70 |
dec.tokenValueEnd() |
| 71 |
|
| 72 |
return err |
| 73 |
} |
| 74 |
|
| 75 |
// Buffered returns a reader of the data remaining in the Decoder's |
| 76 |
// buffer. The reader is valid until the next call to Decode. |
| 77 |
func (dec *Decoder) Buffered() io.Reader { |
| 78 |
return bytes.NewReader(dec.buf[dec.scanp:]) |
| 79 |
} |
| 80 |
|
| 81 |
// readValue reads a JSON value into dec.buf. |
| 82 |
// It returns the length of the encoding. |
| 83 |
func (dec *Decoder) readValue() (int, error) { |
| 84 |
dec.scan.reset() |
| 85 |
|
| 86 |
scanp := dec.scanp |
| 87 |
var err error |
| 88 |
Input: |
| 89 |
for { |
| 90 |
// Look in the buffer for a new value. |
| 91 |
for i, c := range dec.buf[scanp:] { |
| 92 |
dec.scan.bytes++ |
| 93 |
v := dec.scan.step(&dec.scan, c) |
| 94 |
if v == scanEnd { |
| 95 |
scanp += i |
| 96 |
break Input |
| 97 |
} |
| 98 |
// scanEnd is delayed one byte. |
| 99 |
// We might block trying to get that byte from src, |
| 100 |
// so instead invent a space byte. |
| 101 |
if (v == scanEndObject || v == scanEndArray) && dec.scan.step(&dec.scan, ' ') == scanEnd { |
| 102 |
scanp += i + 1 |
| 103 |
break Input |
| 104 |
} |
| 105 |
if v == scanError { |
| 106 |
dec.err = dec.scan.err |
| 107 |
return 0, dec.scan.err |
| 108 |
} |
| 109 |
} |
| 110 |
scanp = len(dec.buf) |
| 111 |
|
| 112 |
// Did the last read have an error? |
| 113 |
// Delayed until now to allow buffer scan. |
| 114 |
if err != nil { |
| 115 |
if err == io.EOF { |
| 116 |
if dec.scan.step(&dec.scan, ' ') == scanEnd { |
| 117 |
break Input |
| 118 |
} |
| 119 |
if nonSpace(dec.buf) { |
| 120 |
err = io.ErrUnexpectedEOF |
| 121 |
} |
| 122 |
} |
| 123 |
dec.err = err |
| 124 |
return 0, err |
| 125 |
} |
| 126 |
|
| 127 |
n := scanp - dec.scanp |
| 128 |
err = dec.refill() |
| 129 |
scanp = dec.scanp + n |
| 130 |
} |
| 131 |
return scanp - dec.scanp, nil |
| 132 |
} |
| 133 |
|
| 134 |
func (dec *Decoder) refill() error { |
| 135 |
// Make room to read more into the buffer. |
| 136 |
// First slide down data already consumed. |
| 137 |
if dec.scanp > 0 { |
| 138 |
n := copy(dec.buf, dec.buf[dec.scanp:]) |
| 139 |
dec.buf = dec.buf[:n] |
| 140 |
dec.scanp = 0 |
| 141 |
} |
| 142 |
|
| 143 |
// Grow buffer if not large enough. |
| 144 |
const minRead = 512 |
| 145 |
if cap(dec.buf)-len(dec.buf) < minRead { |
| 146 |
newBuf := make([]byte, len(dec.buf), 2*cap(dec.buf)+minRead) |
| 147 |
copy(newBuf, dec.buf) |
| 148 |
dec.buf = newBuf |
| 149 |
} |
| 150 |
|
| 151 |
// Read. Delay error for next iteration (after scan). |
| 152 |
n, err := dec.r.Read(dec.buf[len(dec.buf):cap(dec.buf)]) |
| 153 |
dec.buf = dec.buf[0 : len(dec.buf)+n] |
| 154 |
|
| 155 |
return err |
| 156 |
} |
| 157 |
|
| 158 |
func nonSpace(b []byte) bool { |
| 159 |
for _, c := range b { |
| 160 |
if !isSpace(c) { |
| 161 |
return true |
| 162 |
} |
| 163 |
} |
| 164 |
return false |
| 165 |
} |
| 166 |
|
| 167 |
// An Encoder writes JSON objects to an output stream. |
| 168 |
type Encoder struct { |
| 169 |
w io.Writer |
| 170 |
err error |
| 171 |
canonical bool |
| 172 |
} |
| 173 |
|
| 174 |
// NewEncoder returns a new encoder that writes to w. |
| 175 |
func NewEncoder(w io.Writer) *Encoder { |
| 176 |
return &Encoder{w: w} |
| 177 |
} |
| 178 |
|
| 179 |
// Canonical causes the encoder to switch to Canonical JSON mode. |
| 180 |
// Read more at: http://wiki.laptop.org/go/Canonical_JSON |
| 181 |
func (enc *Encoder) Canonical() { enc.canonical = true } |
| 182 |
|
| 183 |
// Encode writes the JSON encoding of v to the stream, |
| 184 |
// followed by a newline character. |
| 185 |
// |
| 186 |
// See the documentation for Marshal for details about the |
| 187 |
// conversion of Go values to JSON. |
| 188 |
func (enc *Encoder) Encode(v interface{}) error { |
| 189 |
if enc.err != nil { |
| 190 |
return enc.err |
| 191 |
} |
| 192 |
e := newEncodeState(enc.canonical) |
| 193 |
err := e.marshal(v) |
| 194 |
if err != nil { |
| 195 |
return err |
| 196 |
} |
| 197 |
|
| 198 |
if !enc.canonical { |
| 199 |
// Terminate each value with a newline. |
| 200 |
// This makes the output look a little nicer |
| 201 |
// when debugging, and some kind of space |
| 202 |
// is required if the encoded value was a number, |
| 203 |
// so that the reader knows there aren't more |
| 204 |
// digits coming. |
| 205 |
e.WriteByte('\n') |
| 206 |
} |
| 207 |
|
| 208 |
if _, err = enc.w.Write(e.Bytes()); err != nil { |
| 209 |
enc.err = err |
| 210 |
} |
| 211 |
encodeStatePool.Put(e) |
| 212 |
return err |
| 213 |
} |
| 214 |
|
| 215 |
// RawMessage is a raw encoded JSON object. |
| 216 |
// It implements Marshaler and Unmarshaler and can |
| 217 |
// be used to delay JSON decoding or precompute a JSON encoding. |
| 218 |
type RawMessage []byte |
| 219 |
|
| 220 |
// MarshalJSON returns *m as the JSON encoding of m. |
| 221 |
func (m *RawMessage) MarshalJSON() ([]byte, error) { |
| 222 |
return *m, nil |
| 223 |
} |
| 224 |
|
| 225 |
// UnmarshalJSON sets *m to a copy of data. |
| 226 |
func (m *RawMessage) UnmarshalJSON(data []byte) error { |
| 227 |
if m == nil { |
| 228 |
return errors.New("json.RawMessage: UnmarshalJSON on nil pointer") |
| 229 |
} |
| 230 |
*m = append((*m)[0:0], data...) |
| 231 |
return nil |
| 232 |
} |
| 233 |
|
| 234 |
var _ Marshaler = (*RawMessage)(nil) |
| 235 |
var _ Unmarshaler = (*RawMessage)(nil) |
| 236 |
|
| 237 |
// A Token holds a value of one of these types: |
| 238 |
// |
| 239 |
// Delim, for the four JSON delimiters [ ] { } |
| 240 |
// bool, for JSON booleans |
| 241 |
// float64, for JSON numbers |
| 242 |
// Number, for JSON numbers |
| 243 |
// string, for JSON string literals |
| 244 |
// nil, for JSON null |
| 245 |
// |
| 246 |
type Token interface{} |
| 247 |
|
| 248 |
const ( |
| 249 |
tokenTopValue = iota |
| 250 |
tokenArrayStart |
| 251 |
tokenArrayValue |
| 252 |
tokenArrayComma |
| 253 |
tokenObjectStart |
| 254 |
tokenObjectKey |
| 255 |
tokenObjectColon |
| 256 |
tokenObjectValue |
| 257 |
tokenObjectComma |
| 258 |
) |
| 259 |
|
| 260 |
// advance tokenstate from a separator state to a value state |
| 261 |
func (dec *Decoder) tokenPrepareForDecode() error { |
| 262 |
// Note: Not calling peek before switch, to avoid |
| 263 |
// putting peek into the standard Decode path. |
| 264 |
// peek is only called when using the Token API. |
| 265 |
switch dec.tokenState { |
| 266 |
case tokenArrayComma: |
| 267 |
c, err := dec.peek() |
| 268 |
if err != nil { |
| 269 |
return err |
| 270 |
} |
| 271 |
if c != ',' { |
| 272 |
return &SyntaxError{"expected comma after array element", 0} |
| 273 |
} |
| 274 |
dec.scanp++ |
| 275 |
dec.tokenState = tokenArrayValue |
| 276 |
case tokenObjectColon: |
| 277 |
c, err := dec.peek() |
| 278 |
if err != nil { |
| 279 |
return err |
| 280 |
} |
| 281 |
if c != ':' { |
| 282 |
return &SyntaxError{"expected colon after object key", 0} |
| 283 |
} |
| 284 |
dec.scanp++ |
| 285 |
dec.tokenState = tokenObjectValue |
| 286 |
} |
| 287 |
return nil |
| 288 |
} |
| 289 |
|
| 290 |
func (dec *Decoder) tokenValueAllowed() bool { |
| 291 |
switch dec.tokenState { |
| 292 |
case tokenTopValue, tokenArrayStart, tokenArrayValue, tokenObjectValue: |
| 293 |
return true |
| 294 |
} |
| 295 |
return false |
| 296 |
} |
| 297 |
|
| 298 |
func (dec *Decoder) tokenValueEnd() { |
| 299 |
switch dec.tokenState { |
| 300 |
case tokenArrayStart, tokenArrayValue: |
| 301 |
dec.tokenState = tokenArrayComma |
| 302 |
case tokenObjectValue: |
| 303 |
dec.tokenState = tokenObjectComma |
| 304 |
} |
| 305 |
} |
| 306 |
|
| 307 |
// A Delim is a JSON array or object delimiter, one of [ ] { or }. |
| 308 |
type Delim rune |
| 309 |
|
| 310 |
func (d Delim) String() string { |
| 311 |
return string(d) |
| 312 |
} |
| 313 |
|
| 314 |
// Token returns the next JSON token in the input stream. |
| 315 |
// At the end of the input stream, Token returns nil, io.EOF. |
| 316 |
// |
| 317 |
// Token guarantees that the delimiters [ ] { } it returns are |
| 318 |
// properly nested and matched: if Token encounters an unexpected |
| 319 |
// delimiter in the input, it will return an error. |
| 320 |
// |
| 321 |
// The input stream consists of basic JSON values—bool, string, |
| 322 |
// number, and null—along with delimiters [ ] { } of type Delim |
| 323 |
// to mark the start and end of arrays and objects. |
| 324 |
// Commas and colons are elided. |
| 325 |
func (dec *Decoder) Token() (Token, error) { |
| 326 |
for { |
| 327 |
c, err := dec.peek() |
| 328 |
if err != nil { |
| 329 |
return nil, err |
| 330 |
} |
| 331 |
switch c { |
| 332 |
case '[': |
| 333 |
if !dec.tokenValueAllowed() { |
| 334 |
return dec.tokenError(c) |
| 335 |
} |
| 336 |
dec.scanp++ |
| 337 |
dec.tokenStack = append(dec.tokenStack, dec.tokenState) |
| 338 |
dec.tokenState = tokenArrayStart |
| 339 |
return Delim('['), nil |
| 340 |
|
| 341 |
case ']': |
| 342 |
if dec.tokenState != tokenArrayStart && dec.tokenState != tokenArrayComma { |
| 343 |
return dec.tokenError(c) |
| 344 |
} |
| 345 |
dec.scanp++ |
| 346 |
dec.tokenState = dec.tokenStack[len(dec.tokenStack)-1] |
| 347 |
dec.tokenStack = dec.tokenStack[:len(dec.tokenStack)-1] |
| 348 |
dec.tokenValueEnd() |
| 349 |
return Delim(']'), nil |
| 350 |
|
| 351 |
case '{': |
| 352 |
if !dec.tokenValueAllowed() { |
| 353 |
return dec.tokenError(c) |
| 354 |
} |
| 355 |
dec.scanp++ |
| 356 |
dec.tokenStack = append(dec.tokenStack, dec.tokenState) |
| 357 |
dec.tokenState = tokenObjectStart |
| 358 |
return Delim('{'), nil |
| 359 |
|
| 360 |
case '}': |
| 361 |
if dec.tokenState != tokenObjectStart && dec.tokenState != tokenObjectComma { |
| 362 |
return dec.tokenError(c) |
| 363 |
} |
| 364 |
dec.scanp++ |
| 365 |
dec.tokenState = dec.tokenStack[len(dec.tokenStack)-1] |
| 366 |
dec.tokenStack = dec.tokenStack[:len(dec.tokenStack)-1] |
| 367 |
dec.tokenValueEnd() |
| 368 |
return Delim('}'), nil |
| 369 |
|
| 370 |
case ':': |
| 371 |
if dec.tokenState != tokenObjectColon { |
| 372 |
return dec.tokenError(c) |
| 373 |
} |
| 374 |
dec.scanp++ |
| 375 |
dec.tokenState = tokenObjectValue |
| 376 |
continue |
| 377 |
|
| 378 |
case ',': |
| 379 |
if dec.tokenState == tokenArrayComma { |
| 380 |
dec.scanp++ |
| 381 |
dec.tokenState = tokenArrayValue |
| 382 |
continue |
| 383 |
} |
| 384 |
if dec.tokenState == tokenObjectComma { |
| 385 |
dec.scanp++ |
| 386 |
dec.tokenState = tokenObjectKey |
| 387 |
continue |
| 388 |
} |
| 389 |
return dec.tokenError(c) |
| 390 |
|
| 391 |
case '"': |
| 392 |
if dec.tokenState == tokenObjectStart || dec.tokenState == tokenObjectKey { |
| 393 |
var x string |
| 394 |
old := dec.tokenState |
| 395 |
dec.tokenState = tokenTopValue |
| 396 |
err := dec.Decode(&x) |
| 397 |
dec.tokenState = old |
| 398 |
if err != nil { |
| 399 |
clearOffset(err) |
| 400 |
return nil, err |
| 401 |
} |
| 402 |
dec.tokenState = tokenObjectColon |
| 403 |
return x, nil |
| 404 |
} |
| 405 |
fallthrough |
| 406 |
|
| 407 |
default: |
| 408 |
if !dec.tokenValueAllowed() { |
| 409 |
return dec.tokenError(c) |
| 410 |
} |
| 411 |
var x interface{} |
| 412 |
if err := dec.Decode(&x); err != nil { |
| 413 |
clearOffset(err) |
| 414 |
return nil, err |
| 415 |
} |
| 416 |
return x, nil |
| 417 |
} |
| 418 |
} |
| 419 |
} |
| 420 |
|
| 421 |
func clearOffset(err error) { |
| 422 |
if s, ok := err.(*SyntaxError); ok { |
| 423 |
s.Offset = 0 |
| 424 |
} |
| 425 |
} |
| 426 |
|
| 427 |
func (dec *Decoder) tokenError(c byte) (Token, error) { |
| 428 |
var context string |
| 429 |
switch dec.tokenState { |
| 430 |
case tokenTopValue: |
| 431 |
context = " looking for beginning of value" |
| 432 |
case tokenArrayStart, tokenArrayValue, tokenObjectValue: |
| 433 |
context = " looking for beginning of value" |
| 434 |
case tokenArrayComma: |
| 435 |
context = " after array element" |
| 436 |
case tokenObjectKey: |
| 437 |
context = " looking for beginning of object key string" |
| 438 |
case tokenObjectColon: |
| 439 |
context = " after object key" |
| 440 |
case tokenObjectComma: |
| 441 |
context = " after object key:value pair" |
| 442 |
} |
| 443 |
return nil, &SyntaxError{"invalid character " + quoteChar(c) + " " + context, 0} |
| 444 |
} |
| 445 |
|
| 446 |
// More reports whether there is another element in the |
| 447 |
// current array or object being parsed. |
| 448 |
func (dec *Decoder) More() bool { |
| 449 |
c, err := dec.peek() |
| 450 |
return err == nil && c != ']' && c != '}' |
| 451 |
} |
| 452 |
|
| 453 |
func (dec *Decoder) peek() (byte, error) { |
| 454 |
var err error |
| 455 |
for { |
| 456 |
for i := dec.scanp; i < len(dec.buf); i++ { |
| 457 |
c := dec.buf[i] |
| 458 |
if isSpace(c) { |
| 459 |
continue |
| 460 |
} |
| 461 |
dec.scanp = i |
| 462 |
return c, nil |
| 463 |
} |
| 464 |
// buffer has been scanned, now report any error |
| 465 |
if err != nil { |
| 466 |
return 0, err |
| 467 |
} |
| 468 |
err = dec.refill() |
| 469 |
} |
| 470 |
} |
| 471 |
|
| 472 |
/* |
| 473 |
TODO |
| 474 |
|
| 475 |
// EncodeToken writes the given JSON token to the stream. |
| 476 |
// It returns an error if the delimiters [ ] { } are not properly used. |
| 477 |
// |
| 478 |
// EncodeToken does not call Flush, because usually it is part of |
| 479 |
// a larger operation such as Encode, and those will call Flush when finished. |
| 480 |
// Callers that create an Encoder and then invoke EncodeToken directly, |
| 481 |
// without using Encode, need to call Flush when finished to ensure that |
| 482 |
// the JSON is written to the underlying writer. |
| 483 |
func (e *Encoder) EncodeToken(t Token) error { |
| 484 |
... |
| 485 |
} |
| 486 |
|
| 487 |
*/ |