github.com/xushiwei/go@v0.0.0-20130601165731-2b9d83f45bc9/doc/articles/json_and_go.html (about) 1 <!--{ 2 "Title": "JSON and Go", 3 "Template": true 4 }--> 5 6 <p> 7 JSON (JavaScript Object Notation) is a simple data interchange format. 8 Syntactically it resembles the objects and lists of JavaScript. It is most 9 commonly used for communication between web back-ends and JavaScript programs 10 running in the browser, but it is used in many other places, too. Its home page, 11 <a href="http://json.org">json.org</a>, provides a wonderfully clear and concise 12 definition of the standard. 13 </p> 14 15 <p> 16 With the <a href="/pkg/encoding/json/">json package</a> it's a snap to read and 17 write JSON data from your Go programs. 18 </p> 19 20 <p> 21 <b>Encoding</b> 22 </p> 23 24 <p> 25 To encode JSON data we use the 26 <a href="/pkg/encoding/json/#Marshal"><code>Marshal</code></a> function. 27 </p> 28 29 <pre> 30 func Marshal(v interface{}) ([]byte, error) 31 </pre> 32 33 <p> 34 Given the Go data structure, <code>Message</code>, 35 </p> 36 37 {{code "/doc/progs/json1.go" `/type Message/` `/STOP/`}} 38 39 <p> 40 and an instance of <code>Message</code> 41 </p> 42 43 {{code "/doc/progs/json1.go" `/m :=/`}} 44 45 <p> 46 we can marshal a JSON-encoded version of <code>m</code> using <code>json.Marshal</code>: 47 </p> 48 49 {{code "/doc/progs/json1.go" `/b, err :=/`}} 50 51 <p> 52 If all is well, <code>err</code> will be <code>nil</code> and <code>b</code> 53 will be a <code>[]byte</code> containing this JSON data: 54 </p> 55 56 <pre> 57 b == []byte(`{"Name":"Alice","Body":"Hello","Time":1294706395881547000}`) 58 </pre> 59 60 <p> 61 Only data structures that can be represented as valid JSON will be encoded: 62 </p> 63 64 <ul> 65 <li> 66 JSON objects only support strings as keys; to encode a Go map type it must be 67 of the form <code>map[string]T</code> (where <code>T</code> is any Go type 68 supported by the json package). 69 </li> 70 <li> 71 Channel, complex, and function types cannot be encoded. 72 </li> 73 <li> 74 Cyclic data structures are not supported; they will cause <code>Marshal</code> 75 to go into an infinite loop. 76 </li> 77 <li> 78 Pointers will be encoded as the values they point to (or 'null' if the pointer 79 is <code>nil</code>). 80 </li> 81 </ul> 82 83 <p> 84 The json package only accesses the exported fields of struct types (those that 85 begin with an uppercase letter). Therefore only the exported fields of a struct 86 will be present in the JSON output. 87 </p> 88 89 <p> 90 <b>Decoding</b> 91 </p> 92 93 <p> 94 To decode JSON data we use the 95 <a href="/pkg/encoding/json/#Unmarshal"><code>Unmarshal</code></a> function. 96 </p> 97 98 <pre> 99 func Unmarshal(data []byte, v interface{}) error 100 </pre> 101 102 <p> 103 We must first create a place where the decoded data will be stored 104 </p> 105 106 {{code "/doc/progs/json1.go" `/var m Message/`}} 107 108 <p> 109 and call <code>json.Unmarshal</code>, passing it a <code>[]byte</code> of JSON 110 data and a pointer to <code>m</code> 111 </p> 112 113 {{code "/doc/progs/json1.go" `/err := json.Unmarshal/`}} 114 115 <p> 116 If <code>b</code> contains valid JSON that fits in <code>m</code>, after the 117 call <code>err</code> will be <code>nil</code> and the data from <code>b</code> 118 will have been stored in the struct <code>m</code>, as if by an assignment 119 like: 120 </p> 121 122 {{code "/doc/progs/json1.go" `/m = Message/` `/STOP/`}} 123 124 <p> 125 How does <code>Unmarshal</code> identify the fields in which to store the 126 decoded data? For a given JSON key <code>"Foo"</code>, <code>Unmarshal</code> 127 will look through the destination struct's fields to find (in order of 128 preference): 129 </p> 130 131 <ul> 132 <li> 133 An exported field with a tag of <code>`json:"Foo"`</code> (see the 134 <a href="/ref/spec#Struct_types">Go spec</a> for more on struct tags), 135 </li> 136 <li> 137 An exported field named <code>"Foo"</code>, or 138 </li> 139 <li> 140 An exported field named <code>"FOO"</code> or <code>"FoO"</code> or some other 141 case-insensitive match of <code>"Foo"</code>. 142 </li> 143 </ul> 144 145 <p> 146 What happens when the structure of the JSON data doesn't exactly match the Go 147 type? 148 </p> 149 150 {{code "/doc/progs/json1.go" `/"Food":"Pickle"/` `/STOP/`}} 151 152 <p> 153 <code>Unmarshal</code> will decode only the fields that it can find in the 154 destination type. In this case, only the <code>Name</code> field of m will be 155 populated, and the <code>Food</code> field will be ignored. This behavior is 156 particularly useful when you wish to pick only a few specific fields out of a 157 large JSON blob. It also means that any unexported fields in the destination 158 struct will be unaffected by <code>Unmarshal</code>. 159 </p> 160 161 <p> 162 But what if you don't know the structure of your JSON data beforehand? 163 </p> 164 165 <p> 166 <b>Generic JSON with <code>interface{}</code></b> 167 </p> 168 169 <p> 170 The <code>interface{}</code> (empty interface) type describes an interface with 171 zero methods. Every Go type implements at least zero methods and therefore 172 satisfies the empty interface. 173 </p> 174 175 <p> 176 The empty interface serves as a general container type: 177 </p> 178 179 {{code "/doc/progs/json2.go" `/var i interface{}/` `/STOP/`}} 180 181 <p> 182 A type assertion accesses the underlying concrete type: 183 </p> 184 185 {{code "/doc/progs/json2.go" `/r := i/` `/STOP/`}} 186 187 <p> 188 Or, if the underlying type is unknown, a type switch determines the type: 189 </p> 190 191 {{code "/doc/progs/json2.go" `/switch v/` `/STOP/`}} 192 193 <p> 194 The json package uses <code>map[string]interface{}</code> and 195 <code>[]interface{}</code> values to store arbitrary JSON objects and arrays; 196 it will happily unmarshal any valid JSON blob into a plain 197 <code>interface{}</code> value. The default concrete Go types are: 198 </p> 199 200 <ul> 201 <li> 202 <code>bool</code> for JSON booleans, 203 </li> 204 <li> 205 <code>float64</code> for JSON numbers, 206 </li> 207 <li> 208 <code>string</code> for JSON strings, and 209 </li> 210 <li> 211 <code>nil</code> for JSON null. 212 </li> 213 </ul> 214 215 <p> 216 <b>Decoding arbitrary data</b> 217 </p> 218 219 <p> 220 Consider this JSON data, stored in the variable <code>b</code>: 221 </p> 222 223 {{code "/doc/progs/json3.go" `/b :=/`}} 224 225 <p> 226 Without knowing this data's structure, we can decode it into an 227 <code>interface{}</code> value with <code>Unmarshal</code>: 228 </p> 229 230 {{code "/doc/progs/json3.go" `/var f interface/` `/STOP/`}} 231 232 <p> 233 At this point the Go value in <code>f</code> would be a map whose keys are 234 strings and whose values are themselves stored as empty interface values: 235 </p> 236 237 {{code "/doc/progs/json3.go" `/f = map/` `/STOP/`}} 238 239 <p> 240 To access this data we can use a type assertion to access <code>f</code>'s 241 underlying <code>map[string]interface{}</code>: 242 </p> 243 244 {{code "/doc/progs/json3.go" `/m := f/`}} 245 246 <p> 247 We can then iterate through the map with a range statement and use a type switch 248 to access its values as their concrete types: 249 </p> 250 251 {{code "/doc/progs/json3.go" `/for k, v/` `/STOP/`}} 252 253 <p> 254 In this way you can work with unknown JSON data while still enjoying the 255 benefits of type safety. 256 </p> 257 258 <p> 259 <b>Reference Types</b> 260 </p> 261 262 <p> 263 Let's define a Go type to contain the data from the previous example: 264 </p> 265 266 {{code "/doc/progs/json4.go" `/type FamilyMember/` `/STOP/`}} 267 268 {{code "/doc/progs/json4.go" `/var m FamilyMember/` `/STOP/`}} 269 270 <p> 271 Unmarshaling that data into a <code>FamilyMember</code> value works as 272 expected, but if we look closely we can see a remarkable thing has happened. 273 With the var statement we allocated a <code>FamilyMember</code> struct, and 274 then provided a pointer to that value to <code>Unmarshal</code>, but at that 275 time the <code>Parents</code> field was a <code>nil</code> slice value. To 276 populate the <code>Parents</code> field, <code>Unmarshal</code> allocated a new 277 slice behind the scenes. This is typical of how <code>Unmarshal</code> works 278 with the supported reference types (pointers, slices, and maps). 279 </p> 280 281 <p> 282 Consider unmarshaling into this data structure: 283 </p> 284 285 <pre> 286 type Foo struct { 287 Bar *Bar 288 } 289 </pre> 290 291 <p> 292 If there were a <code>Bar</code> field in the JSON object, 293 <code>Unmarshal</code> would allocate a new <code>Bar</code> and populate it. 294 If not, <code>Bar</code> would be left as a <code>nil</code> pointer. 295 </p> 296 297 <p> 298 From this a useful pattern arises: if you have an application that receives a 299 few distinct message types, you might define "receiver" structure like 300 </p> 301 302 <pre> 303 type IncomingMessage struct { 304 Cmd *Command 305 Msg *Message 306 } 307 </pre> 308 309 <p> 310 and the sending party can populate the <code>Cmd</code> field and/or the 311 <code>Msg</code> field of the top-level JSON object, depending on the type of 312 message they want to communicate. <code>Unmarshal</code>, when decoding the 313 JSON into an <code>IncomingMessage</code> struct, will only allocate the data 314 structures present in the JSON data. To know which messages to process, the 315 programmer need simply test that either <code>Cmd</code> or <code>Msg</code> is 316 not <code>nil</code>. 317 </p> 318 319 <p> 320 <b>Streaming Encoders and Decoders</b> 321 </p> 322 323 <p> 324 The json package provides <code>Decoder</code> and <code>Encoder</code> types 325 to support the common operation of reading and writing streams of JSON data. 326 The <code>NewDecoder</code> and <code>NewEncoder</code> functions wrap the 327 <a href="/pkg/io/#Reader"><code>io.Reader</code></a> and 328 <a href="/pkg/io/#Writer"><code>io.Writer</code></a> interface types. 329 </p> 330 331 <pre> 332 func NewDecoder(r io.Reader) *Decoder 333 func NewEncoder(w io.Writer) *Encoder 334 </pre> 335 336 <p> 337 Here's an example program that reads a series of JSON objects from standard 338 input, removes all but the <code>Name</code> field from each object, and then 339 writes the objects to standard output: 340 </p> 341 342 {{code "/doc/progs/json5.go" `/package main/` `$`}} 343 344 <p> 345 Due to the ubiquity of Readers and Writers, these <code>Encoder</code> and 346 <code>Decoder</code> types can be used in a broad range of scenarios, such as 347 reading and writing to HTTP connections, WebSockets, or files. 348 </p> 349 350 <p> 351 <b>References</b> 352 </p> 353 354 <p> 355 For more information see the <a href="/pkg/encoding/json/">json package documentation</a>. For an example usage of 356 json see the source files of the <a href="/pkg/net/rpc/jsonrpc/">jsonrpc package</a>. 357 </p>