diff options
| author | Andrew Gerrand <adg@golang.org> | 2011-12-19 11:16:55 +1100 |
|---|---|---|
| committer | Andrew Gerrand <adg@golang.org> | 2011-12-19 11:16:55 +1100 |
| commit | 5ede9df5a0905e79a1ed8d2be75d6c4f2e7a1787 (patch) | |
| tree | aa530f149a7df91aaa6a98420fe24f3965b1bf2e /src/pkg | |
| parent | 12f473f8073ba6a59577967a99849d791f5b81b6 (diff) | |
| download | go-5ede9df5a0905e79a1ed8d2be75d6c4f2e7a1787.tar.xz | |
encoding/json: examples for Marshal and Unmarshal
R=golang-dev, r
CC=golang-dev
https://golang.org/cl/5493075
Diffstat (limited to 'src/pkg')
| -rw-r--r-- | src/pkg/encoding/json/example_test.go | 48 |
1 files changed, 48 insertions, 0 deletions
diff --git a/src/pkg/encoding/json/example_test.go b/src/pkg/encoding/json/example_test.go new file mode 100644 index 0000000000..7f4a78c315 --- /dev/null +++ b/src/pkg/encoding/json/example_test.go @@ -0,0 +1,48 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package json_test + +import ( + "encoding/json" + "fmt" + "os" +) + +// {"ID":1,"Name":"Reds","Colors":["Crimson","Red","Ruby","Maroon"]} +func ExampleMarshal() { + type ColorGroup struct { + ID int + Name string + Colors []string + } + group := ColorGroup{ + ID: 1, + Name: "Reds", + Colors: []string{"Crimson", "Red", "Ruby", "Maroon"}, + } + b, err := json.Marshal(group) + if err != nil { + fmt.Println("error:", err) + } + os.Stdout.Write(b) +} + +// [{Name:Platypus Order:Monotremata} {Name:Quoll Order:Dasyuromorphia}] +func ExampleUnmarshal() { + var jsonBlob = []byte(`[ + {"Name": "Platypus", "Order": "Monotremata"}, + {"Name": "Quoll", "Order": "Dasyuromorphia"} + ]`) + type Animal struct { + Name string + Order string + } + var animals []Animal + err := json.Unmarshal(jsonBlob, &animals) + if err != nil { + fmt.Println("error:", err) + } + fmt.Printf("%+v", animals) +} |
