diff options
Diffstat (limited to 'src/pkg/encoding/json/example_test.go')
-rw-r--r-- | src/pkg/encoding/json/example_test.go | 39 |
1 files changed, 37 insertions, 2 deletions
diff --git a/src/pkg/encoding/json/example_test.go b/src/pkg/encoding/json/example_test.go index 7f4a78c31..b8d150eda 100644 --- a/src/pkg/encoding/json/example_test.go +++ b/src/pkg/encoding/json/example_test.go @@ -7,10 +7,12 @@ package json_test import ( "encoding/json" "fmt" + "io" + "log" "os" + "strings" ) -// {"ID":1,"Name":"Reds","Colors":["Crimson","Red","Ruby","Maroon"]} func ExampleMarshal() { type ColorGroup struct { ID int @@ -27,9 +29,10 @@ func ExampleMarshal() { fmt.Println("error:", err) } os.Stdout.Write(b) + // Output: + // {"ID":1,"Name":"Reds","Colors":["Crimson","Red","Ruby","Maroon"]} } -// [{Name:Platypus Order:Monotremata} {Name:Quoll Order:Dasyuromorphia}] func ExampleUnmarshal() { var jsonBlob = []byte(`[ {"Name": "Platypus", "Order": "Monotremata"}, @@ -45,4 +48,36 @@ func ExampleUnmarshal() { fmt.Println("error:", err) } fmt.Printf("%+v", animals) + // Output: + // [{Name:Platypus Order:Monotremata} {Name:Quoll Order:Dasyuromorphia}] +} + +// This example uses a Decoder to decode a stream of distinct JSON values. +func ExampleDecoder() { + 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) + } + // Output: + // Ed: Knock knock. + // Sam: Who's there? + // Ed: Go fmt. + // Sam: Go fmt who? + // Ed: Go fmt yourself! } |