github.com/varialus/godfly@v0.0.0-20130904042352-1934f9f095ab/src/pkg/encoding/json/example_test.go (about) 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 "encoding/json" 9 "fmt" 10 "io" 11 "log" 12 "os" 13 "strings" 14 ) 15 16 func ExampleMarshal() { 17 type ColorGroup struct { 18 ID int 19 Name string 20 Colors []string 21 } 22 group := ColorGroup{ 23 ID: 1, 24 Name: "Reds", 25 Colors: []string{"Crimson", "Red", "Ruby", "Maroon"}, 26 } 27 b, err := json.Marshal(group) 28 if err != nil { 29 fmt.Println("error:", err) 30 } 31 os.Stdout.Write(b) 32 // Output: 33 // {"ID":1,"Name":"Reds","Colors":["Crimson","Red","Ruby","Maroon"]} 34 } 35 36 func ExampleUnmarshal() { 37 var jsonBlob = []byte(`[ 38 {"Name": "Platypus", "Order": "Monotremata"}, 39 {"Name": "Quoll", "Order": "Dasyuromorphia"} 40 ]`) 41 type Animal struct { 42 Name string 43 Order string 44 } 45 var animals []Animal 46 err := json.Unmarshal(jsonBlob, &animals) 47 if err != nil { 48 fmt.Println("error:", err) 49 } 50 fmt.Printf("%+v", animals) 51 // Output: 52 // [{Name:Platypus Order:Monotremata} {Name:Quoll Order:Dasyuromorphia}] 53 } 54 55 // This example uses a Decoder to decode a stream of distinct JSON values. 56 func ExampleDecoder() { 57 const jsonStream = ` 58 {"Name": "Ed", "Text": "Knock knock."} 59 {"Name": "Sam", "Text": "Who's there?"} 60 {"Name": "Ed", "Text": "Go fmt."} 61 {"Name": "Sam", "Text": "Go fmt who?"} 62 {"Name": "Ed", "Text": "Go fmt yourself!"} 63 ` 64 type Message struct { 65 Name, Text string 66 } 67 dec := json.NewDecoder(strings.NewReader(jsonStream)) 68 for { 69 var m Message 70 if err := dec.Decode(&m); err == io.EOF { 71 break 72 } else if err != nil { 73 log.Fatal(err) 74 } 75 fmt.Printf("%s: %s\n", m.Name, m.Text) 76 } 77 // Output: 78 // Ed: Knock knock. 79 // Sam: Who's there? 80 // Ed: Go fmt. 81 // Sam: Go fmt who? 82 // Ed: Go fmt yourself! 83 }