Black Lives Matter. Support the Equal Justice Initiative.

Source file src/encoding/json/stream.go

Documentation: encoding/json

     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 values 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  	scanned int64 // amount of data already scanned
    20  	scan    scanner
    21  	err     error
    22  
    23  	tokenState int
    24  	tokenStack []int
    25  }
    26  
    27  // NewDecoder returns a new decoder that reads from r.
    28  //
    29  // The decoder introduces its own buffering and may
    30  // read data from r beyond the JSON values requested.
    31  func NewDecoder(r io.Reader) *Decoder {
    32  	return &Decoder{r: r}
    33  }
    34  
    35  // UseNumber causes the Decoder to unmarshal a number into an interface{} as a
    36  // Number instead of as a float64.
    37  func (dec *Decoder) UseNumber() { dec.d.useNumber = true }
    38  
    39  // DisallowUnknownFields causes the Decoder to return an error when the destination
    40  // is a struct and the input contains object keys which do not match any
    41  // non-ignored, exported fields in the destination.
    42  func (dec *Decoder) DisallowUnknownFields() { dec.d.disallowUnknownFields = true }
    43  
    44  // Decode reads the next JSON-encoded value from its
    45  // input and stores it in the value pointed to by v.
    46  //
    47  // See the documentation for Unmarshal for details about
    48  // the conversion of JSON into a Go value.
    49  func (dec *Decoder) Decode(v interface{}) error {
    50  	if dec.err != nil {
    51  		return dec.err
    52  	}
    53  
    54  	if err := dec.tokenPrepareForDecode(); err != nil {
    55  		return err
    56  	}
    57  
    58  	if !dec.tokenValueAllowed() {
    59  		return &SyntaxError{msg: "not at beginning of value", Offset: dec.InputOffset()}
    60  	}
    61  
    62  	// Read whole value into buffer.
    63  	n,