forked from ateleshev/go-json
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexample_test.go
95 lines (82 loc) · 1.77 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
// Copyright 2013 Gary Burd. 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 (
"fmt"
"strconv"
"strings"
"github.com/garyburd/json"
)
const jsonText = `
[
{
"name": "redigo",
"keywords": ["database", "redis"],
"imports": 10
},
{
"name": "mgo",
"keywords": ["database", "mongodb"],
"imports": 22
}
]
`
var emptySlice = make([]interface{}, 0, 0)
func decodeValue(s *json.Scanner) (interface{}, error) {
switch s.Kind() {
case json.Number:
return strconv.ParseFloat(string(s.Value()), 64)
case json.String:
return string(s.Value()), nil
case json.Array:
v := emptySlice
as := s.ArrayScanner()
for as.Scan() {
subv, err := decodeValue(s)
if err != nil {
return v, err
}
v = append(v, subv)
}
return v, s.Err()
case json.Object:
v := make(map[string]interface{})
os := s.ObjectScanner()
for os.Scan() {
subv, err := decodeValue(s)
if err != nil {
return v, err
}
v[os.Name()] = subv
}
return v, s.Err()
case json.Bool:
return s.BoolValue(), nil
case json.Null:
return nil, nil
default:
return nil, fmt.Errorf("unexpected %v", s.Kind())
}
}
// This example shows how to decode a JSON value to a tree of maps and slices.
func ExampleScanner() {
s := json.NewScanner(strings.NewReader(jsonText))
if !s.Scan() {
fmt.Printf("error %v\n", s.Err())
return
}
v, err := decodeValue(s)
if err != nil {
fmt.Printf("error %v\n", err)
return
}
s.Scan()
if s.Err() != nil {
fmt.Printf("error %v\n", s.Err())
return
}
fmt.Println(v)
// Output:
// [map[name:redigo keywords:[database redis] imports:10] map[name:mgo keywords:[database mongodb] imports:22]]
}