forked from daviddengcn/ljson
/
example_test.go
68 lines (64 loc) · 1.37 KB
/
example_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// 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 ljson_test
import (
"fmt"
"github.com/daviddengcn/ljson"
"io"
"log"
"strings"
)
func ExampleUnmarshal() {
var jsonBlob = []byte(`[
{
Name : "Platypus"
Order: "Monotremata"
}
{
Name : "Quoll"
Order: "Dasyuromorphia"
}
]`)
type Animal struct {
Name string
Order string
}
var animals []Animal
err := ljson.Unmarshal(jsonBlob, &animals)
if err != nil {
fmt.Println("error:", err)
}
fmt.Printf("%+v", animals)
// Output:
// [{Name:Platypus Order:Monotremata} {Name:Quoll Order:Dasyuromorphia}]
}
// This example uses a Decoder to decode a stream of distinct JSON values.
func ExampleDecoder() {
const jsonStream = `
{Name: "Ed" Text: "Knock knock."}
{Name: "Sam" Text: "Who's there?"}
{Name: "Ed" Text: "Go fmt."}
{Name: "Sam" Text: "Go fmt who?"}
{Name: "Ed" Text: "Go fmt yourself!"}
`
type Message struct {
Name, Text string
}
dec := ljson.NewDecoder(strings.NewReader(jsonStream))
for {
var m Message
if err := dec.Decode(&m); err == io.EOF {
break
} else if err != nil {
log.Fatal(err)
}
fmt.Printf("%s: %s\n", m.Name, m.Text)
}
// Output:
// Ed: Knock knock.
// Sam: Who's there?
// Ed: Go fmt.
// Sam: Go fmt who?
// Ed: Go fmt yourself!
}