Home | History | Annotate | Download | only in json
      1 // Copyright 2011 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_test
      6 
      7 import (
      8 	"bytes"
      9 	"encoding/json"
     10 	"fmt"
     11 	"io"
     12 	"log"
     13 	"os"
     14 	"strings"
     15 )
     16 
     17 func ExampleMarshal() {
     18 	type ColorGroup struct {
     19 		ID     int
     20 		Name   string
     21 		Colors []string
     22 	}
     23 	group := ColorGroup{
     24 		ID:     1,
     25 		Name:   "Reds",
     26 		Colors: []string{"Crimson", "Red", "Ruby", "Maroon"},
     27 	}
     28 	b, err := json.Marshal(group)
     29 	if err != nil {
     30 		fmt.Println("error:", err)
     31 	}
     32 	os.Stdout.Write(b)
     33 	// Output:
     34 	// {"ID":1,"Name":"Reds","Colors":["Crimson","Red","Ruby","Maroon"]}
     35 }
     36 
     37 func ExampleUnmarshal() {
     38 	var jsonBlob = []byte(`[
     39 		{"Name": "Platypus", "Order": "Monotremata"},
     40 		{"Name": "Quoll",    "Order": "Dasyuromorphia"}
     41 	]`)
     42 	type Animal struct {
     43 		Name  string
     44 		Order string
     45 	}
     46 	var animals []Animal
     47 	err := json.Unmarshal(jsonBlob, &animals)
     48 	if err != nil {
     49 		fmt.Println("error:", err)
     50 	}
     51 	fmt.Printf("%+v", animals)
     52 	// Output:
     53 	// [{Name:Platypus Order:Monotremata} {Name:Quoll Order:Dasyuromorphia}]
     54 }
     55 
     56 // This example uses a Decoder to decode a stream of distinct JSON values.
     57 func ExampleDecoder() {
     58 	const jsonStream = `
     59 		{"Name": "Ed", "Text": "Knock knock."}
     60 		{"Name": "Sam", "Text": "Who's there?"}
     61 		{"Name": "Ed", "Text": "Go fmt."}
     62 		{"Name": "Sam", "Text": "Go fmt who?"}
     63 		{"Name": "Ed", "Text": "Go fmt yourself!"}
     64 	`
     65 	type Message struct {
     66 		Name, Text string
     67 	}
     68 	dec := json.NewDecoder(strings.NewReader(jsonStream))
     69 	for {
     70 		var m Message
     71 		if err := dec.Decode(&m); err == io.EOF {
     72 			break
     73 		} else if err != nil {
     74 			log.Fatal(err)
     75 		}
     76 		fmt.Printf("%s: %s\n", m.Name, m.Text)
     77 	}
     78 	// Output:
     79 	// Ed: Knock knock.
     80 	// Sam: Who's there?
     81 	// Ed: Go fmt.
     82 	// Sam: Go fmt who?
     83 	// Ed: Go fmt yourself!
     84 }
     85 
     86 // This example uses a Decoder to decode a stream of distinct JSON values.
     87 func ExampleDecoder_Token() {
     88 	const jsonStream = `
     89 		{"Message": "Hello", "Array": [1, 2, 3], "Null": null, "Number": 1.234}
     90 	`
     91 	dec := json.NewDecoder(strings.NewReader(jsonStream))
     92 	for {
     93 		t, err := dec.Token()
     94 		if err == io.EOF {
     95 			break
     96 		}
     97 		if err != nil {
     98 			log.Fatal(err)
     99 		}
    100 		fmt.Printf("%T: %v", t, t)
    101 		if dec.More() {
    102 			fmt.Printf(" (more)")
    103 		}
    104 		fmt.Printf("\n")
    105 	}
    106 	// Output:
    107 	// json.Delim: { (more)
    108 	// string: Message (more)
    109 	// string: Hello (more)
    110 	// string: Array (more)
    111 	// json.Delim: [ (more)
    112 	// float64: 1 (more)
    113 	// float64: 2 (more)
    114 	// float64: 3
    115 	// json.Delim: ] (more)
    116 	// string: Null (more)
    117 	// <nil>: <nil> (more)
    118 	// string: Number (more)
    119 	// float64: 1.234
    120 	// json.Delim: }
    121 }
    122 
    123 // This example uses a Decoder to decode a streaming array of JSON objects.
    124 func ExampleDecoder_Decode_stream() {
    125 	const jsonStream = `
    126 		[
    127 			{"Name": "Ed", "Text": "Knock knock."},
    128 			{"Name": "Sam", "Text": "Who's there?"},
    129 			{"Name": "Ed", "Text": "Go fmt."},
    130 			{"Name": "Sam", "Text": "Go fmt who?"},
    131 			{"Name": "Ed", "Text": "Go fmt yourself!"}
    132 		]
    133 	`
    134 	type Message struct {
    135 		Name, Text string
    136 	}
    137 	dec := json.NewDecoder(strings.NewReader(jsonStream))
    138 
    139 	// read open bracket
    140 	t, err := dec.Token()
    141 	if err != nil {
    142 		log.Fatal(err)
    143 	}
    144 	fmt.Printf("%T: %v\n", t, t)
    145 
    146 	var m Message
    147 	// while the array contains values
    148 	for dec.More() {
    149 
    150 		// decode an array value (Message)
    151 		err := dec.Decode(&m)
    152 		if err != nil {
    153 			log.Fatal(err)
    154 		}
    155 
    156 		fmt.Printf("%v: %v\n", m.Name, m.Text)
    157 	}
    158 
    159 	// read closing bracket
    160 	t, err = dec.Token()
    161 	if err != nil {
    162 		log.Fatal(err)
    163 	}
    164 	fmt.Printf("%T: %v\n", t, t)
    165 
    166 	// Output:
    167 	// json.Delim: [
    168 	// Ed: Knock knock.
    169 	// Sam: Who's there?
    170 	// Ed: Go fmt.
    171 	// Sam: Go fmt who?
    172 	// Ed: Go fmt yourself!
    173 	// json.Delim: ]
    174 
    175 }
    176 
    177 // This example uses RawMessage to delay parsing part of a JSON message.
    178 func ExampleRawMessage() {
    179 	type Color struct {
    180 		Space string
    181 		Point json.RawMessage // delay parsing until we know the color space
    182 	}
    183 	type RGB struct {
    184 		R uint8
    185 		G uint8
    186 		B uint8
    187 	}
    188 	type YCbCr struct {
    189 		Y  uint8
    190 		Cb int8
    191 		Cr int8
    192 	}
    193 
    194 	var j = []byte(`[
    195 		{"Space": "YCbCr", "Point": {"Y": 255, "Cb": 0, "Cr": -10}},
    196 		{"Space": "RGB",   "Point": {"R": 98, "G": 218, "B": 255}}
    197 	]`)
    198 	var colors []Color
    199 	err := json.Unmarshal(j, &colors)
    200 	if err != nil {
    201 		log.Fatalln("error:", err)
    202 	}
    203 
    204 	for _, c := range colors {
    205 		var dst interface{}
    206 		switch c.Space {
    207 		case "RGB":
    208 			dst = new(RGB)
    209 		case "YCbCr":
    210 			dst = new(YCbCr)
    211 		}
    212 		err := json.Unmarshal(c.Point, dst)
    213 		if err != nil {
    214 			log.Fatalln("error:", err)
    215 		}
    216 		fmt.Println(c.Space, dst)
    217 	}
    218 	// Output:
    219 	// YCbCr &{255 0 -10}
    220 	// RGB &{98 218 255}
    221 }
    222 
    223 func ExampleIndent() {
    224 	type Road struct {
    225 		Name   string
    226 		Number int
    227 	}
    228 	roads := []Road{
    229 		{"Diamond Fork", 29},
    230 		{"Sheep Creek", 51},
    231 	}
    232 
    233 	b, err := json.Marshal(roads)
    234 	if err != nil {
    235 		log.Fatal(err)
    236 	}
    237 
    238 	var out bytes.Buffer
    239 	json.Indent(&out, b, "=", "\t")
    240 	out.WriteTo(os.Stdout)
    241 	// Output:
    242 	// [
    243 	// =	{
    244 	// =		"Name": "Diamond Fork",
    245 	// =		"Number": 29
    246 	// =	},
    247 	// =	{
    248 	// =		"Name": "Sheep Creek",
    249 	// =		"Number": 51
    250 	// =	}
    251 	// =]
    252 }
    253