This example uses a Decoder to decode a stream of distinct JSON values.
()
| 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() { |