|
|
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="theme-color" content="#375EAB">
<title>json - The Go Programming Language</title>
<link type="text/css" rel="stylesheet" href="../../../lib/godoc/style.css">
<link rel="stylesheet" href="../../../lib/godoc/jquery.treeview.css"> <script type="text/javascript">window.initFuncs = [];</script> </head> <body>
<div id='lowframe' style="position: fixed; bottom: 0; left: 0; height: 0; width: 100%; border-top: thin solid grey; background-color: white; overflow: auto;"> ... </div><!-- #lowframe -->
<div id="topbar" class="wide"><div class="container"> <div class="top-heading" id="heading-wide"><a href="http://localhost:6060/">The Go Programming Language</a></div> <div class="top-heading" id="heading-narrow"><a href="http://localhost:6060/">Go</a></div> <a href="index.html#" id="menu-button"><span id="menu-button-arrow">▽</span></a> <form method="GET" action="http://localhost:6060/search"> <div id="menu"> <a href="http://localhost:6060/doc/">Documents</a> <a href="http://localhost:6060/pkg/">Packages</a> <a href="http://localhost:6060/project/">The Project</a> <a href="http://localhost:6060/help/">Help</a> <a href="http://localhost:6060/blog/">Blog</a>
<input type="text" id="search" name="q" class="inactive" value="Search" placeholder="Search"> </div> </form>
</div></div>
<div id="page" class="wide"> <div class="container">
<h1>Package json</h1>
<div id="nav"></div>
<!--
Copyright 2009 The Go Authors. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. --> <!--
Note: Static (i.e., not template-generated) href and id attributes start with "pkg-" to make it impossible for them to conflict with generated attributes (some of which correspond to Go identifiers). -->
<script type='text/javascript'> document.ANALYSIS_DATA = null; document.CALLGRAPH = null; </script>
<div id="short-nav"> <dl> <dd><code>import "encoding/json"</code></dd> </dl> <dl> <dd><a href="index.html#pkg-overview" class="overviewLink">Overview</a></dd> <dd><a href="index.html#pkg-index" class="indexLink">Index</a></dd> <dd><a href="index.html#pkg-examples" class="examplesLink">Examples</a></dd> </dl> </div> <!-- The package's Name is printed as title by the top-level template --> <div id="pkg-overview" class="toggleVisible"> <div class="collapsed"> <h2 class="toggleButton" title="Click to show Overview section">Overview ▹</h2> </div> <div class="expanded"> <h2 class="toggleButton" title="Click to hide Overview section">Overview ▾</h2> <p> Package json implements encoding and decoding of JSON objects as defined in RFC 4627. The mapping between JSON objects and Go values is described in the documentation for the Marshal and Unmarshal functions. </p> <p> See "JSON and Go" for an introduction to this package: <a href="https://golang.org/doc/articles/json_and_go.html">https://golang.org/doc/articles/json_and_go.html</a> </p>
</div> </div>
<div id="pkg-index" class="toggleVisible"> <div class="collapsed"> <h2 class="toggleButton" title="Click to show Index section">Index ▹</h2> </div> <div class="expanded"> <h2 class="toggleButton" title="Click to hide Index section">Index ▾</h2>
<!-- Table of contents for API; must be named manual-nav to turn off auto nav. --> <div id="manual-nav"> <dl> <dd><a href="index.html#Compact">func Compact(dst *bytes.Buffer, src []byte) error</a></dd> <dd><a href="index.html#HTMLEscape">func HTMLEscape(dst *bytes.Buffer, src []byte)</a></dd> <dd><a href="index.html#Indent">func Indent(dst *bytes.Buffer, src []byte, prefix, indent string) error</a></dd> <dd><a href="index.html#Marshal">func Marshal(v interface{}) ([]byte, error)</a></dd> <dd><a href="index.html#MarshalIndent">func MarshalIndent(v interface{}, prefix, indent string) ([]byte, error)</a></dd> <dd><a href="index.html#Unmarshal">func Unmarshal(data []byte, v interface{}) error</a></dd> <dd><a href="index.html#Decoder">type Decoder</a></dd> <dd> <a href="index.html#NewDecoder">func NewDecoder(r io.Reader) *Decoder</a></dd> <dd> <a href="index.html#Decoder.Buffered">func (dec *Decoder) Buffered() io.Reader</a></dd> <dd> <a href="index.html#Decoder.Decode">func (dec *Decoder) Decode(v interface{}) error</a></dd> <dd> <a href="index.html#Decoder.More">func (dec *Decoder) More() bool</a></dd> <dd> <a href="index.html#Decoder.Token">func (dec *Decoder) Token() (Token, error)</a></dd> <dd> <a href="index.html#Decoder.UseNumber">func (dec *Decoder) UseNumber()</a></dd> <dd><a href="index.html#Delim">type Delim</a></dd> <dd> <a href="index.html#Delim.String">func (d Delim) String() string</a></dd> <dd><a href="index.html#Encoder">type Encoder</a></dd> <dd> <a href="index.html#NewEncoder">func NewEncoder(w io.Writer) *Encoder</a></dd> <dd> <a href="index.html#Encoder.Encode">func (enc *Encoder) Encode(v interface{}) error</a></dd> <dd><a href="index.html#InvalidUTF8Error">type InvalidUTF8Error</a></dd> <dd> <a href="index.html#InvalidUTF8Error.Error">func (e *InvalidUTF8Error) Error() string</a></dd> <dd><a href="index.html#InvalidUnmarshalError">type InvalidUnmarshalError</a></dd> <dd> <a href="index.html#InvalidUnmarshalError.Error">func (e *InvalidUnmarshalError) Error() string</a></dd> <dd><a href="index.html#Marshaler">type Marshaler</a></dd> <dd><a href="index.html#MarshalerError">type MarshalerError</a></dd> <dd> <a href="index.html#MarshalerError.Error">func (e *MarshalerError) Error() string</a></dd> <dd><a href="index.html#Number">type Number</a></dd> <dd> <a href="index.html#Number.Float64">func (n Number) Float64() (float64, error)</a></dd> <dd> <a href="index.html#Number.Int64">func (n Number) Int64() (int64, error)</a></dd> <dd> <a href="index.html#Number.String">func (n Number) String() string</a></dd> <dd><a href="index.html#RawMessage">type RawMessage</a></dd> <dd> <a href="index.html#RawMessage.MarshalJSON">func (m *RawMessage) MarshalJSON() ([]byte, error)</a></dd> <dd> <a href="index.html#RawMessage.UnmarshalJSON">func (m *RawMessage) UnmarshalJSON(data []byte) error</a></dd> <dd><a href="index.html#SyntaxError">type SyntaxError</a></dd> <dd> <a href="index.html#SyntaxError.Error">func (e *SyntaxError) Error() string</a></dd> <dd><a href="index.html#Token">type Token</a></dd> <dd><a href="index.html#UnmarshalFieldError">type UnmarshalFieldError</a></dd> <dd> <a href="index.html#UnmarshalFieldError.Error">func (e *UnmarshalFieldError) Error() string</a></dd> <dd><a href="index.html#UnmarshalTypeError">type UnmarshalTypeError</a></dd> <dd> <a href="index.html#UnmarshalTypeError.Error">func (e *UnmarshalTypeError) Error() string</a></dd> <dd><a href="index.html#Unmarshaler">type Unmarshaler</a></dd> <dd><a href="index.html#UnsupportedTypeError">type UnsupportedTypeError</a></dd> <dd> <a href="index.html#UnsupportedTypeError.Error">func (e *UnsupportedTypeError) Error() string</a></dd> <dd><a href="index.html#UnsupportedValueError">type UnsupportedValueError</a></dd> <dd> <a href="index.html#UnsupportedValueError.Error">func (e *UnsupportedValueError) Error() string</a></dd> </dl> </div><!-- #manual-nav -->
<div id="pkg-examples"> <h4>Examples</h4> <dl> <dd><a class="exampleLink" href="index.html#example_Decoder">Decoder</a></dd> <dd><a class="exampleLink" href="index.html#example_Decoder_Decode_stream">Decoder.Decode (Stream)</a></dd> <dd><a class="exampleLink" href="index.html#example_Decoder_Token">Decoder.Token</a></dd> <dd><a class="exampleLink" href="index.html#example_Indent">Indent</a></dd> <dd><a class="exampleLink" href="index.html#example_Marshal">Marshal</a></dd> <dd><a class="exampleLink" href="index.html#example_RawMessage">RawMessage</a></dd> <dd><a class="exampleLink" href="index.html#example_Unmarshal">Unmarshal</a></dd> </dl> </div>
<h4>Package files</h4> <p> <span style="font-size:90%"> <a href="http://localhost:6060/src/encoding/json/decode.go">decode.go</a> <a href="http://localhost:6060/src/encoding/json/encode.go">encode.go</a> <a href="http://localhost:6060/src/encoding/json/fold.go">fold.go</a> <a href="http://localhost:6060/src/encoding/json/indent.go">indent.go</a> <a href="http://localhost:6060/src/encoding/json/scanner.go">scanner.go</a> <a href="http://localhost:6060/src/encoding/json/stream.go">stream.go</a> <a href="http://localhost:6060/src/encoding/json/tags.go">tags.go</a> </span> </p> </div><!-- .expanded --> </div><!-- #pkg-index -->
<div id="pkg-callgraph" class="toggle" style="display: none"> <div class="collapsed"> <h2 class="toggleButton" title="Click to show Internal Call Graph section">Internal call graph ▹</h2> </div> <!-- .expanded --> <div class="expanded"> <h2 class="toggleButton" title="Click to hide Internal Call Graph section">Internal call graph ▾</h2> <p> In the call graph viewer below, each node is a function belonging to this package and its children are the functions it calls—perhaps dynamically. </p> <p> The root nodes are the entry points of the package: functions that may be called from outside the package. There may be non-exported or anonymous functions among them if they are called dynamically from another package. </p> <p> Click a node to visit that function's source code. From there you can visit its callers by clicking its declaring <code>func</code> token. </p> <p> Functions may be omitted if they were determined to be unreachable in the particular programs or tests that were analyzed. </p> <!-- Zero means show all package entry points. --> <ul style="margin-left: 0.5in" id="callgraph-0" class="treeview"></ul> </div> </div> <!-- #pkg-callgraph -->
<h2 id="Compact">func <a href="http://localhost:6060/src/encoding/json/indent.go?s=285:334#L1">Compact</a></h2> <pre>func Compact(dst *<a href="../../bytes/index.html">bytes</a>.<a href="../../bytes/index.html#Buffer">Buffer</a>, src []<a href="../../builtin/index.html#byte">byte</a>) <a href="../../builtin/index.html#error">error</a></pre> <p> Compact appends to dst the JSON-encoded src with insignificant space characters elided. </p>
<h2 id="HTMLEscape">func <a href="http://localhost:6060/src/encoding/json/encode.go?s=6459:6505#L156">HTMLEscape</a></h2> <pre>func HTMLEscape(dst *<a href="../../bytes/index.html">bytes</a>.<a href="../../bytes/index.html#Buffer">Buffer</a>, src []<a href="../../builtin/index.html#byte">byte</a>)</pre> <p> HTMLEscape appends to dst the JSON-encoded src with <, >, &, U+2028 and U+2029 characters inside string literals changed to \u003c, \u003e, \u0026, \u2028, \u2029 so that the JSON will be safe to embed inside HTML <script> tags. For historical reasons, web browsers don't honor standard HTML escaping within <script> tags, so an alternative JSON encoding must be used. </p>
<h2 id="Indent">func <a href="http://localhost:6060/src/encoding/json/indent.go?s=2193:2264#L69">Indent</a></h2> <pre>func Indent(dst *<a href="../../bytes/index.html">bytes</a>.<a href="../../bytes/index.html#Buffer">Buffer</a>, src []<a href="../../builtin/index.html#byte">byte</a>, prefix, indent <a href="../../builtin/index.html#string">string</a>) <a href="../../builtin/index.html#error">error</a></pre> <p> Indent appends to dst an indented form of the JSON-encoded src. Each element in a JSON object or array begins on a new, indented line beginning with prefix followed by one or more copies of indent according to the indentation nesting. The data appended to dst does not begin with the prefix nor any indentation, to make it easier to embed inside other formatted JSON data. Although leading space characters (space, tab, carriage return, newline) at the beginning of src are dropped, trailing space characters at the end of src are preserved and copied to dst. For example, if src has no trailing spaces, neither will dst; if src ends in a trailing newline, so will dst. </p>
<div id="example_Indent" class="toggle"> <div class="collapsed"> <p class="exampleHeading toggleButton">▹ <span class="text">Example</span></p> </div> <div class="expanded"> <p class="exampleHeading toggleButton">▾ <span class="text">Example</span></p> <p>Code:</p> <pre class="code">type Road struct { Name string Number int } roads := []Road{ {"Diamond Fork", 29}, {"Sheep Creek", 51}, }
b, err := json.Marshal(roads) if err != nil { log.Fatal(err) }
var out bytes.Buffer json.Indent(&out, b, "=", "\t") out.WriteTo(os.Stdout) <span class="comment"></pre> <p>Output:</p> <pre class="output">[ = { = "Name": "Diamond Fork", = "Number": 29 = }, = { = "Name": "Sheep Creek", = "Number": 51 = } =] </pre> </div> </div>
<h2 id="Marshal">func <a href="http://localhost:6060/src/encoding/json/encode.go?s=5584:5627#L127">Marshal</a></h2> <pre>func Marshal(v interface{}) ([]<a href="../../builtin/index.html#byte">byte</a>, <a href="../../builtin/index.html#error">error</a>)</pre> <p> Marshal returns the JSON encoding of v. </p> <p> Marshal traverses the value v recursively. If an encountered value implements the Marshaler interface and is not a nil pointer, Marshal calls its MarshalJSON method to produce JSON. If no MarshalJSON method is present but the value implements encoding.TextMarshaler instead, Marshal calls its MarshalText method. The nil pointer exception is not strictly necessary but mimics a similar, necessary exception in the behavior of UnmarshalJSON. </p> <p> Otherwise, Marshal uses the following type-dependent default encodings: </p> <p> Boolean values encode as JSON booleans. </p> <p> Floating point, integer, and Number values encode as JSON numbers. </p> <p> String values encode as JSON strings coerced to valid UTF-8, replacing invalid bytes with the Unicode replacement rune. The angle brackets "<" and ">" are escaped to "\u003c" and "\u003e" to keep some browsers from misinterpreting JSON output as HTML. Ampersand "&" is also escaped to "\u0026" for the same reason. </p> <p> Array and slice values encode as JSON arrays, except that []byte encodes as a base64-encoded string, and a nil slice encodes as the null JSON object. </p> <p> Struct values encode as JSON objects. Each exported struct field becomes a member of the object unless </p> <pre>- the field's tag is "-", or - the field is empty and its tag specifies the "omitempty" option. </pre> <p> The empty values are false, 0, any nil pointer or interface value, and any array, slice, map, or string of length zero. The object's default key string is the struct field name but can be specified in the struct field's tag value. The "json" key in the struct field's tag value is the key name, followed by an optional comma and options. Examples: </p> <pre>// Field is ignored by this package. Field int `json:"-"`
// Field appears in JSON as key "myName". Field int `json:"myName"`
// Field appears in JSON as key "myName" and // the field is omitted from the object if its value is empty, // as defined above. Field int `json:"myName,omitempty"`
// Field appears in JSON as key "Field" (the default), but // the field is skipped if empty. // Note the leading comma. Field int `json:",omitempty"` </pre> <p> The "string" option signals that a field is stored as JSON inside a JSON-encoded string. It applies only to fields of string, floating point, integer, or boolean types. This extra level of encoding is sometimes used when communicating with JavaScript programs: </p> <pre>Int64String int64 `json:",string"` </pre> <p> The key name will be used if it's a non-empty string consisting of only Unicode letters, digits, dollar signs, percent signs, hyphens, underscores and slashes. </p> <p> Anonymous struct fields are usually marshaled as if their inner exported fields were fields in the outer struct, subject to the usual Go visibility rules amended as described in the next paragraph. An anonymous struct field with a name given in its JSON tag is treated as having that name, rather than being anonymous. An anonymous struct field of interface type is treated the same as having that type as its name, rather than being anonymous. </p> <p> The Go visibility rules for struct fields are amended for JSON when deciding which field to marshal or unmarshal. If there are multiple fields at the same level, and that level is the least nested (and would therefore be the nesting level selected by the usual Go rules), the following extra rules apply: </p> <p> 1) Of those fields, if any are JSON-tagged, only tagged fields are considered, even if there are multiple untagged fields that would otherwise conflict. 2) If there is exactly one field (tagged or not according to the first rule), that is selected. 3) Otherwise there are multiple fields, and all are ignored; no error occurs. </p> <p> Handling of anonymous struct fields is new in Go 1.1. Prior to Go 1.1, anonymous struct fields were ignored. To force ignoring of an anonymous struct field in both current and earlier versions, give the field a JSON tag of "-". </p> <p> Map values encode as JSON objects. The map's key type must be string; the map keys are used as JSON object keys, subject to the UTF-8 coercion described for string values above. </p> <p> Pointer values encode as the value pointed to. A nil pointer encodes as the null JSON object. </p> <p> Interface values encode as the value contained in the interface. A nil interface value encodes as the null JSON object. </p> <p> Channel, complex, and function values cannot be encoded in JSON. Attempting to encode such a value causes Marshal to return an UnsupportedTypeError. </p> <p> JSON cannot represent cyclic data structures and Marshal does not handle them. Passing cyclic structures to Marshal will result in an infinite recursion. </p>
<div id="example_Marshal" class="toggle"> <div class="collapsed"> <p class="exampleHeading toggleButton">▹ <span class="text">Example</span></p> </div> <div class="expanded"> <p class="exampleHeading toggleButton">▾ <span class="text">Example</span></p> <p>Code:</p> <pre class="code">type ColorGroup struct { ID int Name string Colors []string } group := ColorGroup{ ID: 1, Name: "Reds", Colors: []string{"Crimson", "Red", "Ruby", "Maroon"}, } b, err := json.Marshal(group) if err != nil { fmt.Println("error:", err) } os.Stdout.Write(b) <span class="comment"></pre> <p>Output:</p> <pre class="output">{"ID":1,"Name":"Reds","Colors":["Crimson","Red","Ruby","Maroon"]} </pre> </div> </div>
<h2 id="MarshalIndent">func <a href="http://localhost:6060/src/encoding/json/encode.go?s=5810:5882#L137">MarshalIndent</a></h2> <pre>func MarshalIndent(v interface{}, prefix, indent <a href="../../builtin/index.html#string">string</a>) ([]<a href="../../builtin/index.html#byte">byte</a>, <a href="../../builtin/index.html#error">error</a>)</pre> <p> MarshalIndent is like Marshal but applies Indent to format the output. </p>
<h2 id="Unmarshal">func <a href="http://localhost:6060/src/encoding/json/decode.go?s=3303:3351#L75">Unmarshal</a></h2> <pre>func Unmarshal(data []<a href="../../builtin/index.html#byte">byte</a>, v interface{}) <a href="../../builtin/index.html#error">error</a></pre> <p> Unmarshal parses the JSON-encoded data and stores the result in the value pointed to by v. </p> <p> Unmarshal uses the inverse of the encodings that Marshal uses, allocating maps, slices, and pointers as necessary, with the following additional rules: </p> <p> To unmarshal JSON into a pointer, Unmarshal first handles the case of the JSON being the JSON literal null. In that case, Unmarshal sets the pointer to nil. Otherwise, Unmarshal unmarshals the JSON into the value pointed at by the pointer. If the pointer is nil, Unmarshal allocates a new value for it to point to. </p> <p> To unmarshal JSON into a struct, Unmarshal matches incoming object keys to the keys used by Marshal (either the struct field name or its tag), preferring an exact match but also accepting a case-insensitive match. Unmarshal will only set exported fields of the struct. </p> <p> To unmarshal JSON into an interface value, Unmarshal stores one of these in the interface value: </p> <pre>bool, for JSON booleans float64, for JSON numbers string, for JSON strings []interface{}, for JSON arrays map[string]interface{}, for JSON objects nil for JSON null </pre> <p> To unmarshal a JSON array into a slice, Unmarshal resets the slice length to zero and then appends each element to the slice. As a special case, to unmarshal an empty JSON array into a slice, Unmarshal replaces the slice with a new empty slice. </p> <p> To unmarshal a JSON array into a Go array, Unmarshal decodes JSON array elements into corresponding Go array elements. If the Go array is smaller than the JSON array, the additional JSON array elements are discarded. If the JSON array is smaller than the Go array, the additional Go array elements are set to zero values. </p> <p> To unmarshal a JSON object into a string-keyed map, Unmarshal first establishes a map to use, If the map is nil, Unmarshal allocates a new map. Otherwise Unmarshal reuses the existing map, keeping existing entries. Unmarshal then stores key-value pairs from the JSON object into the map. </p> <p> If a JSON value is not appropriate for a given target type, or if a JSON number overflows the target type, Unmarshal skips that field and completes the unmarshaling as best it can. If no more serious errors are encountered, Unmarshal returns an UnmarshalTypeError describing the earliest such error. </p> <p> The JSON null value unmarshals into an interface, map, pointer, or slice by setting that Go value to nil. Because null is often used in JSON to mean “not present,” unmarshaling a JSON null into any other Go type has no effect on the value and produces no error. </p> <p> When unmarshaling quoted strings, invalid UTF-8 or invalid UTF-16 surrogate pairs are not treated as an error. Instead, they are replaced by the Unicode replacement character U+FFFD. </p>
<div id="example_Unmarshal" class="toggle"> <div class="collapsed"> <p class="exampleHeading toggleButton">▹ <span class="text">Example</span></p> </div> <div class="expanded"> <p class="exampleHeading toggleButton">▾ <span class="text">Example</span></p> <p>Code:</p> <pre class="code">var jsonBlob = []byte(`[ {"Name": "Platypus", "Order": "Monotremata"}, {"Name": "Quoll", "Order": "Dasyuromorphia"} ]`) type Animal struct { Name string Order string } var animals []Animal err := json.Unmarshal(jsonBlob, &animals) if err != nil { fmt.Println("error:", err) } fmt.Printf("%+v", animals) <span class="comment"></pre> <p>Output:</p> <pre class="output">[{Name:Platypus Order:Monotremata} {Name:Quoll Order:Dasyuromorphia}] </pre> </div> </div>
<h2 id="Decoder">type <a href="http://localhost:6060/src/encoding/json/stream.go?s=278:456#L4">Decoder</a></h2> <pre>type Decoder struct { <span class="comment">// contains filtered or unexported fields</span> }</pre> <p> A Decoder reads and decodes JSON objects from an input stream. </p>
<div id="example_Decoder" class="toggle"> <div class="collapsed"> <p class="exampleHeading toggleButton">▹ <span class="text">Example</span></p> </div> <div class="expanded"> <p class="exampleHeading toggleButton">▾ <span class="text">Example</span></p> <p>This example uses a Decoder to decode a stream of distinct JSON values. </p> <p>Code:</p> <pre class="code">const jsonStream = ` {"Name": "Ed", "Text": "Knock knock."} {"Name": "Sam", "Text": "Who's there?"} {"Name": "Ed", "Text": "Go fmt."} {"Name": "Sam", "Text": "Go fmt who?"} {"Name": "Ed", "Text": "Go fmt yourself!"} ` type Message struct { Name, Text string } dec := json.NewDecoder(strings.NewReader(jsonStream)) for { var m Message if err := dec.Decode(&m); err == io.EOF { break } else if err != nil { log.Fatal(err) } fmt.Printf("%s: %s\n", m.Name, m.Text) } <span class="comment"></pre> <p>Output:</p> <pre class="output">Ed: Knock knock. Sam: Who's there? Ed: Go fmt. Sam: Go fmt who? Ed: Go fmt yourself! </pre> </div> </div>
<h3 id="NewDecoder">func <a href="http://localhost:6060/src/encoding/json/stream.go?s=622:659#L20">NewDecoder</a></h3> <pre>func NewDecoder(r <a href="../../io/index.html">io</a>.<a href="../../io/index.html#Reader">Reader</a>) *<a href="index.html#Decoder">Decoder</a></pre> <p> NewDecoder returns a new decoder that reads from r. </p> <p> The decoder introduces its own buffering and may read data from r beyond the JSON values requested. </p>
<h3 id="Decoder.Buffered">func (*Decoder) <a href="http://localhost:6060/src/encoding/json/stream.go?s=1866:1906#L67">Buffered</a></h3> <pre>func (dec *<a href="index.html#Decoder">Decoder</a>) Buffered() <a href="../../io/index.html">io</a>.<a href="../../io/index.html#Reader">Reader</a></pre> <p> Buffered returns a reader of the data remaining in the Decoder's buffer. The reader is valid until the next call to Decode. </p>
<h3 id="Decoder.Decode">func (*Decoder) <a href="http://localhost:6060/src/encoding/json/stream.go?s=1071:1118#L33">Decode</a></h3> <pre>func (dec *<a href="index.html#Decoder">Decoder</a>) Decode(v interface{}) <a href="../../builtin/index.html#error">error</a></pre> <p> Decode reads the next JSON-encoded value from its input and stores it in the value pointed to by v. </p> <p> See the documentation for Unmarshal for details about the conversion of JSON into a Go value. </p>
<div id="example_Decoder_Decode_stream" class="toggle"> <div class="collapsed"> <p class="exampleHeading toggleButton">▹ <span class="text">Example (Stream)</span></p> </div> <div class="expanded"> <p class="exampleHeading toggleButton">▾ <span class="text">Example (Stream)</span></p> <p>This example uses a Decoder to decode a streaming array of JSON objects. </p> <p>Code:</p> <pre class="code">const jsonStream = ` [ {"Name": "Ed", "Text": "Knock knock."}, {"Name": "Sam", "Text": "Who's there?"}, {"Name": "Ed", "Text": "Go fmt."}, {"Name": "Sam", "Text": "Go fmt who?"}, {"Name": "Ed", "Text": "Go fmt yourself!"} ] ` type Message struct { Name, Text string } dec := json.NewDecoder(strings.NewReader(jsonStream))
<span class="comment">// read open bracket</span> t, err := dec.Token() if err != nil { log.Fatal(err) } fmt.Printf("%T: %v\n", t, t)
var m Message <span class="comment">// while the array contains values</span> for dec.More() {
<span class="comment">// decode an array value (Message)</span> err := dec.Decode(&m) if err != nil { log.Fatal(err) }
fmt.Printf("%v: %v\n", m.Name, m.Text) }
<span class="comment">// read closing bracket</span> t, err = dec.Token() if err != nil { log.Fatal(err) } fmt.Printf("%T: %v\n", t, t)
<span class="comment"></pre> <p>Output:</p> <pre class="output">json.Delim: [ Ed: Knock knock. Sam: Who's there? Ed: Go fmt. Sam: Go fmt who? Ed: Go fmt yourself! json.Delim: ] </pre> </div> </div>
<h3 id="Decoder.More">func (*Decoder) <a href="http://localhost:6060/src/encoding/json/stream.go?s=10642:10673#L431">More</a></h3> <pre>func (dec *<a href="index.html#Decoder">Decoder</a>) More() <a href="../../builtin/index.html#bool">bool</a></pre> <p> More reports whether there is another element in the current array or object being parsed. </p>
<h3 id="Decoder.Token">func (*Decoder) <a href="http://localhost:6060/src/encoding/json/stream.go?s=7656:7698#L308">Token</a></h3> <pre>func (dec *<a href="index.html#Decoder">Decoder</a>) Token() (<a href="index.html#Token">Token</a>, <a href="../../builtin/index.html#error">error</a>)</pre> <p> Token returns the next JSON token in the input stream. At the end of the input stream, Token returns nil, io.EOF. </p> <p> Token guarantees that the delimiters [ ] { } it returns are properly nested and matched: if Token encounters an unexpected delimiter in the input, it will return an error. </p> <p> The input stream consists of basic JSON values—bool, string, number, and null—along with delimiters [ ] { } of type Delim to mark the start and end of arrays and objects. Commas and colons are elided. </p>
<div id="example_Decoder_Token" class="toggle"> <div class="collapsed"> <p class="exampleHeading toggleButton">▹ <span class="text">Example</span></p> </div> <div class="expanded"> <p class="exampleHeading toggleButton">▾ <span class="text">Example</span></p> <p>This example uses a Decoder to decode a stream of distinct JSON values. </p> <p>Code:</p> <pre class="code">const jsonStream = ` {"Message": "Hello", "Array": [1, 2, 3], "Null": null, "Number": 1.234} ` dec := json.NewDecoder(strings.NewReader(jsonStream)) for { t, err := dec.Token() if err == io.EOF { break } if err != nil { log.Fatal(err) } fmt.Printf("%T: %v", t, t) if dec.More() { fmt.Printf(" (more)") } fmt.Printf("\n") } <span class="comment"></pre> <p>Output:</p> <pre class="output">json.Delim: { (more) string: Message (more) string: Hello (more) string: Array (more) json.Delim: [ (more) float64: 1 (more) float64: 2 (more) float64: 3 json.Delim: ] (more) string: Null (more) <nil>: <nil> (more) string: Number (more) float64: 1.234 json.Delim: } </pre> </div> </div>
<h3 id="Decoder.UseNumber">func (*Decoder) <a href="http://localhost:6060/src/encoding/json/stream.go?s=802:833#L26">UseNumber</a></h3> <pre>func (dec *<a href="index.html#Decoder">Decoder</a>) UseNumber()</pre> <p> UseNumber causes the Decoder to unmarshal a number into an interface{} as a Number instead of as a float64. </p>
<h2 id="Delim">type <a href="http://localhost:6060/src/encoding/json/stream.go?s=7061:7076#L291">Delim</a></h2> <pre>type Delim <a href="../../builtin/index.html#rune">rune</a></pre> <p> A Delim is a JSON array or object delimiter, one of [ ] { or }. </p>
<h3 id="Delim.String">func (Delim) <a href="http://localhost:6060/src/encoding/json/stream.go?s=7078:7108#L293">String</a></h3> <pre>func (d <a href="index.html#Delim">Delim</a>) String() <a href="../../builtin/index.html#string">string</a></pre> <h2 id="Encoder">type <a href="http://localhost:6060/src/encoding/json/stream.go?s=3912:3961#L158">Encoder</a></h2> <pre>type Encoder struct { <span class="comment">// contains filtered or unexported fields</span> }</pre> <p> An Encoder writes JSON objects to an output stream. </p>
<h3 id="NewEncoder">func <a href="http://localhost:6060/src/encoding/json/stream.go?s=4017:4054#L164">NewEncoder</a></h3> <pre>func NewEncoder(w <a href="../../io/index.html">io</a>.<a href="../../io/index.html#Writer">Writer</a>) *<a href="index.html#Encoder">Encoder</a></pre> <p> NewEncoder returns a new encoder that writes to w. </p>
<h3 id="Encoder.Encode">func (*Encoder) <a href="http://localhost:6060/src/encoding/json/stream.go?s=4272:4319#L173">Encode</a></h3> <pre>func (enc *<a href="index.html#Encoder">Encoder</a>) Encode(v interface{}) <a href="../../builtin/index.html#error">error</a></pre> <p> Encode writes the JSON encoding of v to the stream, followed by a newline character. </p> <p> See the documentation for Marshal for details about the conversion of Go values to JSON. </p>
<h2 id="InvalidUTF8Error">type <a href="http://localhost:6060/src/encoding/json/encode.go?s=8162:8252#L216">InvalidUTF8Error</a></h2> <pre>type InvalidUTF8Error struct { S <a href="../../builtin/index.html#string">string</a> <span class="comment">// the whole string value that caused the error</span> }</pre> <p> Before Go 1.2, an InvalidUTF8Error was returned by Marshal when attempting to encode a string value with invalid UTF-8 sequences. As of Go 1.2, Marshal instead coerces the string to valid UTF-8 by replacing invalid bytes with the Unicode replacement rune U+FFFD. This error is no longer generated but is kept for backwards compatibility with programs that might mention it. </p>
<h3 id="InvalidUTF8Error.Error">func (*InvalidUTF8Error) <a href="http://localhost:6060/src/encoding/json/encode.go?s=8254:8295#L220">Error</a></h3> <pre>func (e *<a href="index.html#InvalidUTF8Error">InvalidUTF8Error</a>) Error() <a href="../../builtin/index.html#string">string</a></pre> <h2 id="InvalidUnmarshalError">type <a href="http://localhost:6060/src/encoding/json/decode.go?s=5033:5089#L125">InvalidUnmarshalError</a></h2> <pre>type InvalidUnmarshalError struct { Type <a href="../../reflect/index.html">reflect</a>.<a href="../../reflect/index.html#Type">Type</a> }</pre> <p> An InvalidUnmarshalError describes an invalid argument passed to Unmarshal. (The argument to Unmarshal must be a non-nil pointer.) </p>
<h3 id="InvalidUnmarshalError.Error">func (*InvalidUnmarshalError) <a href="http://localhost:6060/src/encoding/json/decode.go?s=5091:5137#L129">Error</a></h3> <pre>func (e *<a href="index.html#InvalidUnmarshalError">InvalidUnmarshalError</a>) Error() <a href="../../builtin/index.html#string">string</a></pre> <h2 id="Marshaler">type <a href="http://localhost:6060/src/encoding/json/encode.go?s=7272:7331#L187">Marshaler</a></h2> <pre>type Marshaler interface { MarshalJSON() ([]<a href="../../builtin/index.html#byte">byte</a>, <a href="../../builtin/index.html#error">error</a>) }</pre> <p> Marshaler is the interface implemented by objects that can marshal themselves into valid JSON. </p>
<h2 id="MarshalerError">type <a href="http://localhost:6060/src/encoding/json/encode.go?s=8364:8425#L224">MarshalerError</a></h2> <pre>type MarshalerError struct { Type <a href="../../reflect/index.html">reflect</a>.<a href="../../reflect/index.html#Type">Type</a> Err <a href="../../builtin/index.html#error">error</a> }</pre>
<h3 id="MarshalerError.Error">func (*MarshalerError) <a href="http://localhost:6060/src/encoding/json/encode.go?s=8427:8466#L229">Error</a></h3> <pre>func (e *<a href="index.html#MarshalerError">MarshalerError</a>) Error() <a href="../../builtin/index.html#string">string</a></pre> <h2 id="Number">type <a href="http://localhost:6060/src/encoding/json/decode.go?s=5895:5913#L163">Number</a></h2> <pre>type Number <a href="../../builtin/index.html#string">string</a></pre> <p> A Number represents a JSON number literal. </p>
<h3 id="Number.Float64">func (Number) <a href="http://localhost:6060/src/encoding/json/decode.go?s=6063:6105#L169">Float64</a></h3> <pre>func (n <a href="index.html#Number">Number</a>) Float64() (<a href="../../builtin/index.html#float64">float64</a>, <a href="../../builtin/index.html#error">error</a>)</pre> <p> Float64 returns the number as a float64. </p>
<h3 id="Number.Int64">func (Number) <a href="http://localhost:6060/src/encoding/json/decode.go?s=6194:6232#L174">Int64</a></h3> <pre>func (n <a href="index.html#Number">Number</a>) Int64() (<a href="../../builtin/index.html#int64">int64</a>, <a href="../../builtin/index.html#error">error</a>)</pre> <p> Int64 returns the number as an int64. </p>
<h3 id="Number.String">func (Number) <a href="http://localhost:6060/src/encoding/json/decode.go?s=5965:5996#L166">String</a></h3> <pre>func (n <a href="index.html#Number">Number</a>) String() <a href="../../builtin/index.html#string">string</a></pre> <p> String returns the literal text of the number. </p>
<h2 id="RawMessage">type <a href="http://localhost:6060/src/encoding/json/stream.go?s=4976:4998#L201">RawMessage</a></h2> <pre>type RawMessage []<a href="../../builtin/index.html#byte">byte</a></pre> <p> RawMessage is a raw encoded JSON object. It implements Marshaler and Unmarshaler and can be used to delay JSON decoding or precompute a JSON encoding. </p>
<div id="example_RawMessage" class="toggle"> <div class="collapsed"> <p class="exampleHeading toggleButton">▹ <span class="text">Example</span></p> </div> <div class="expanded"> <p class="exampleHeading toggleButton">▾ <span class="text">Example</span></p> <p>This example uses RawMessage to delay parsing part of a JSON message. </p> <p>Code:</p> <pre class="code">type Color struct { Space string Point json.RawMessage <span class="comment">// delay parsing until we know the color space</span> } type RGB struct { R uint8 G uint8 B uint8 } type YCbCr struct { Y uint8 Cb int8 Cr int8 }
var j = []byte(`[ {"Space": "YCbCr", "Point": {"Y": 255, "Cb": 0, "Cr": -10}}, {"Space": "RGB", "Point": {"R": 98, "G": 218, "B": 255}} ]`) var colors []Color err := json.Unmarshal(j, &colors) if err != nil { log.Fatalln("error:", err) }
for _, c := range colors { var dst interface{} switch c.Space { case "RGB": dst = new(RGB) case "YCbCr": dst = new(YCbCr) } err := json.Unmarshal(c.Point, dst) if err != nil { log.Fatalln("error:", err) } fmt.Println(c.Space, dst) } <span class="comment"></pre> <p>Output:</p> <pre class="output">YCbCr &{255 0 -10} RGB &{98 218 255} </pre> </div> </div>
<h3 id="RawMessage.MarshalJSON">func (*RawMessage) <a href="http://localhost:6060/src/encoding/json/stream.go?s=5053:5103#L204">MarshalJSON</a></h3> <pre>func (m *<a href="index.html#RawMessage">RawMessage</a>) MarshalJSON() ([]<a href="../../builtin/index.html#byte">byte</a>, <a href="../../builtin/index.html#error">error</a>)</pre> <p> MarshalJSON returns *m as the JSON encoding of m. </p>
<h3 id="RawMessage.UnmarshalJSON">func (*RawMessage) <a href="http://localhost:6060/src/encoding/json/stream.go?s=5169:5222#L209">UnmarshalJSON</a></h3> <pre>func (m *<a href="index.html#RawMessage">RawMessage</a>) UnmarshalJSON(data []<a href="../../builtin/index.html#byte">byte</a>) <a href="../../builtin/index.html#error">error</a></pre> <p> UnmarshalJSON sets *m to a copy of data. </p>
<h2 id="SyntaxError">type <a href="http://localhost:6060/src/encoding/json/scanner.go?s=1933:2059#L54">SyntaxError</a></h2> <pre>type SyntaxError struct { Offset <a href="../../builtin/index.html#int64">int64</a> <span class="comment">// error occurred after reading Offset bytes</span> <span class="comment">// contains filtered or unexported fields</span> }</pre> <p> A SyntaxError is a description of a JSON syntax error. </p>
<h3 id="SyntaxError.Error">func (*SyntaxError) <a href="http://localhost:6060/src/encoding/json/scanner.go?s=2061:2097#L59">Error</a></h3> <pre>func (e *<a href="index.html#SyntaxError">SyntaxError</a>) Error() <a href="../../builtin/index.html#string">string</a></pre> <h2 id="Token">type <a href="http://localhost:6060/src/encoding/json/stream.go?s=5680:5702#L229">Token</a></h2> <pre>type Token interface{}</pre> <p> A Token holds a value of one of these types: </p> <pre>Delim, for the four JSON delimiters [ ] { } bool, for JSON booleans float64, for JSON numbers Number, for JSON numbers string, for JSON string literals nil, for JSON null </pre>
<h2 id="UnmarshalFieldError">type <a href="http://localhost:6060/src/encoding/json/decode.go?s=4605:4701#L113">UnmarshalFieldError</a></h2> <pre>type UnmarshalFieldError struct { Key <a href="../../builtin/index.html#string">string</a> Type <a href="../../reflect/index.html">reflect</a>.<a href="../../reflect/index.html#Type">Type</a> Field <a href="../../reflect/index.html">reflect</a>.<a href="../../reflect/index.html#StructField">StructField</a> }</pre> <p> An UnmarshalFieldError describes a JSON object key that led to an unexported (and therefore unwritable) struct field. (No longer used; kept for compatibility.) </p>
<h3 id="UnmarshalFieldError.Error">func (*UnmarshalFieldError) <a href="http://localhost:6060/src/encoding/json/decode.go?s=4703:4747#L119">Error</a></h3> <pre>func (e *<a href="index.html#UnmarshalFieldError">UnmarshalFieldError</a>) Error() <a href="../../builtin/index.html#string">string</a></pre> <h2 id="UnmarshalTypeError">type <a href="http://localhost:6060/src/encoding/json/decode.go?s=4045:4295#L100">UnmarshalTypeError</a></h2> <pre>type UnmarshalTypeError struct { Value <a href="../../builtin/index.html#string">string</a> <span class="comment">// description of JSON value - "bool", "array", "number -5"</span> Type <a href="../../reflect/index.html">reflect</a>.<a href="../../reflect/index.html#Type">Type</a> <span class="comment">// type of Go value it could not be assigned to</span> Offset <a href="../../builtin/index.html#int64">int64</a> <span class="comment">// error occurred after reading Offset bytes</span> }</pre> <p> An UnmarshalTypeError describes a JSON value that was not appropriate for a value of a specific Go type. </p>
<h3 id="UnmarshalTypeError.Error">func (*UnmarshalTypeError) <a href="http://localhost:6060/src/encoding/json/decode.go?s=4297:4340#L106">Error</a></h3> <pre>func (e *<a href="index.html#UnmarshalTypeError">UnmarshalTypeError</a>) Error() <a href="../../builtin/index.html#string">string</a></pre> <h2 id="Unmarshaler">type <a href="http://localhost:6060/src/encoding/json/decode.go?s=3873:3932#L94">Unmarshaler</a></h2> <pre>type Unmarshaler interface { UnmarshalJSON([]<a href="../../builtin/index.html#byte">byte</a>) <a href="../../builtin/index.html#error">error</a> }</pre> <p> Unmarshaler is the interface implemented by objects that can unmarshal a JSON description of themselves. The input can be assumed to be a valid encoding of a JSON value. UnmarshalJSON must copy the JSON data if it wishes to retain the data after returning. </p>
<h2 id="UnsupportedTypeError">type <a href="http://localhost:6060/src/encoding/json/encode.go?s=7439:7494#L193">UnsupportedTypeError</a></h2> <pre>type UnsupportedTypeError struct { Type <a href="../../reflect/index.html">reflect</a>.<a href="../../reflect/index.html#Type">Type</a> }</pre> <p> An UnsupportedTypeError is returned by Marshal when attempting to encode an unsupported value type. </p>
<h3 id="UnsupportedTypeError.Error">func (*UnsupportedTypeError) <a href="http://localhost:6060/src/encoding/json/encode.go?s=7496:7541#L197">Error</a></h3> <pre>func (e *<a href="index.html#UnsupportedTypeError">UnsupportedTypeError</a>) Error() <a href="../../builtin/index.html#string">string</a></pre> <h2 id="UnsupportedValueError">type <a href="http://localhost:6060/src/encoding/json/encode.go?s=7600:7672#L201">UnsupportedValueError</a></h2> <pre>type UnsupportedValueError struct { Value <a href="../../reflect/index.html">reflect</a>.<a href="../../reflect/index.html#Value">Value</a> Str <a href="../../builtin/index.html#string">string</a> }</pre>
<h3 id="UnsupportedValueError.Error">func (*UnsupportedValueError) <a href="http://localhost:6060/src/encoding/json/encode.go?s=7674:7720#L206">Error</a></h3> <pre>func (e *<a href="index.html#UnsupportedValueError">UnsupportedValueError</a>) Error() <a href="../../builtin/index.html#string">string</a></pre>
<div id="footer"> Build version go1.6.<br> Except as <a href="https://developers.google.com/site-policies#restrictions">noted</a>, the content of this page is licensed under the Creative Commons Attribution 3.0 License, and code is licensed under a <a href="http://localhost:6060/LICENSE">BSD license</a>.<br> <a href="http://localhost:6060/doc/tos.html">Terms of Service</a> | <a href="http://www.google.com/intl/en/policies/privacy/">Privacy Policy</a> </div>
</div><!-- .container --> </div><!-- #page -->
<!-- TODO(adonovan): load these from <head> using "defer" attribute? --> <script type="text/javascript" src="../../../lib/godoc/jquery.js"></script> <script type="text/javascript" src="../../../lib/godoc/jquery.treeview.js"></script> <script type="text/javascript" src="../../../lib/godoc/jquery.treeview.edit.js"></script>
<script type="text/javascript" src="../../../lib/godoc/godocs.js"></script>
</body> </html>
|