Source file
doc/progs/json3.go
1
2
3
4
5 package main
6
7 import (
8 "encoding/json"
9 "fmt"
10 "log"
11 "reflect"
12 )
13
14 func Decode() {
15 b := []byte(`{"Name":"Wednesday","Age":6,"Parents":["Gomez","Morticia"]}`)
16
17 var f interface{}
18 err := json.Unmarshal(b, &f)
19
20
21
22 if err != nil {
23 panic(err)
24 }
25
26 expected := map[string]interface{}{
27 "Name": "Wednesday",
28 "Age": float64(6),
29 "Parents": []interface{}{
30 "Gomez",
31 "Morticia",
32 },
33 }
34
35 if !reflect.DeepEqual(f, expected) {
36 log.Panicf("Error unmarshaling %q, expected %q, got %q", b, expected, f)
37 }
38
39 f = map[string]interface{}{
40 "Name": "Wednesday",
41 "Age": 6,
42 "Parents": []interface{}{
43 "Gomez",
44 "Morticia",
45 },
46 }
47
48
49
50 m := f.(map[string]interface{})
51
52 for k, v := range m {
53 switch vv := v.(type) {
54 case string:
55 fmt.Println(k, "is string", vv)
56 case int:
57 fmt.Println(k, "is int", vv)
58 case []interface{}:
59 fmt.Println(k, "is an array:")
60 for i, u := range vv {
61 fmt.Println(i, u)
62 }
63 default:
64 fmt.Println(k, "is of a type I don't know how to handle")
65 }
66 }
67
68
69 }
70
71 func main() {
72 Decode()
73 }
74
View as plain text