This example uses a Decoder to decode a streaming array of JSON objects.
()
| 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 | // while the array contains values |
| 147 | for dec.More() { |
| 148 | var m Message |
| 149 | // decode an array value (Message) |
| 150 | err := dec.Decode(&m) |
| 151 | if err != nil { |
| 152 | log.Fatal(err) |
| 153 | } |
| 154 | |
| 155 | fmt.Printf("%v: %v\n", m.Name, m.Text) |
| 156 | } |
| 157 | |
| 158 | // read closing bracket |
| 159 | t, err = dec.Token() |
| 160 | if err != nil { |
| 161 | log.Fatal(err) |
| 162 | } |
| 163 | fmt.Printf("%T: %v\n", t, t) |
| 164 | |
| 165 | // Output: |
| 166 | // json.Delim: [ |
| 167 | // Ed: Knock knock. |
| 168 | // Sam: Who's there? |
| 169 | // Ed: Go fmt. |
| 170 | // Sam: Go fmt who? |
| 171 | // Ed: Go fmt yourself! |
| 172 | // json.Delim: ] |
| 173 | } |
| 174 | |
| 175 | // This example uses RawMessage to delay parsing part of a JSON message. |
| 176 | func ExampleRawMessage_unmarshal() { |