/
decode_ex_test.go
80 lines (70 loc) · 1.47 KB
/
decode_ex_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
package jsonex_test
import (
"fmt"
"strings"
"testing"
"go.oneofone.dev/jsonex"
)
func TestDecodeItem(t *testing.T) {
data := `[{"a":1},{"a":2},{"c":{"a":5}},5,"test","x",null]`
dec := jsonex.NewDecoder(strings.NewReader(data))
var out []any
for dec.More() {
var v any
if err := dec.DecodeValue(&v); err != nil {
t.Fatal(err)
}
out = append(out, v)
}
j, _ := jsonex.Marshal(out)
if string(j) != data {
t.Fatalf("expected %s, got %s", data, j)
}
dec = jsonex.NewDecoder(strings.NewReader(`{"foo": "bar", "baz": "qux"}`))
// Decode the first key
key, err := dec.DecodeKey()
if err != nil {
panic(err)
}
fmt.Println(string(key))
// Decode the first value
var value string
err = dec.DecodeValue(&value)
if err != nil {
panic(err)
}
fmt.Println(string(value))
// Decode the second key
key, err = dec.DecodeKey()
if err != nil {
panic(err)
}
fmt.Println(string(key))
// Decode the second value
err = dec.DecodeValue(&value)
if err != nil {
panic(err)
}
fmt.Println(string(value))
}
func TestDecodeKeyValue(t *testing.T) {
data := `{"a":1,"b":2,"c":{"a":5}}`
dec := jsonex.NewDecoder(strings.NewReader(data))
out := map[string]any{}
for dec.More() {
key, err := dec.DecodeKey()
if err != nil {
t.Fatal(err)
}
var v any
if err := dec.DecodeValue(&v); err != nil {
t.Fatal(err)
}
out[key] = v
t.Logf("%q: %v", key, v)
}
j, _ := jsonex.Marshal(out)
if string(j) != data {
t.Fatalf("expected %s, got %s", data, j)
}
}