Shenghou Ma | 5b7562d | 2012-09-03 03:49:03 +0800 | [diff] [blame] | 1 | // compile |
| 2 | |
Francisco Souza | 289a357 | 2012-03-22 18:25:40 +1100 | [diff] [blame] | 3 | // Copyright 2012 The Go Authors. All rights reserved. |
| 4 | // Use of this source code is governed by a BSD-style |
| 5 | // license that can be found in the LICENSE file. |
| 6 | |
| 7 | package main |
| 8 | |
| 9 | import ( |
| 10 | "encoding/json" |
| 11 | "fmt" |
| 12 | "log" |
| 13 | "reflect" |
| 14 | ) |
| 15 | |
| 16 | func Decode() { |
| 17 | b := []byte(`{"Name":"Wednesday","Age":6,"Parents":["Gomez","Morticia"]}`) |
| 18 | |
| 19 | var f interface{} |
| 20 | err := json.Unmarshal(b, &f) |
| 21 | |
| 22 | // STOP OMIT |
| 23 | |
| 24 | if err != nil { |
| 25 | panic(err) |
| 26 | } |
| 27 | |
| 28 | expected := map[string]interface{}{ |
| 29 | "Name": "Wednesday", |
| 30 | "Age": float64(6), |
| 31 | "Parents": []interface{}{ |
| 32 | "Gomez", |
| 33 | "Morticia", |
| 34 | }, |
| 35 | } |
| 36 | |
| 37 | if !reflect.DeepEqual(f, expected) { |
| 38 | log.Panicf("Error unmarshalling %q, expected %q, got %q", b, expected, f) |
| 39 | } |
| 40 | |
| 41 | f = map[string]interface{}{ |
| 42 | "Name": "Wednesday", |
| 43 | "Age": 6, |
| 44 | "Parents": []interface{}{ |
| 45 | "Gomez", |
| 46 | "Morticia", |
| 47 | }, |
| 48 | } |
| 49 | |
| 50 | // STOP OMIT |
| 51 | |
| 52 | m := f.(map[string]interface{}) |
| 53 | |
| 54 | for k, v := range m { |
| 55 | switch vv := v.(type) { |
| 56 | case string: |
| 57 | fmt.Println(k, "is string", vv) |
| 58 | case int: |
| 59 | fmt.Println(k, "is int", vv) |
| 60 | case []interface{}: |
| 61 | fmt.Println(k, "is an array:") |
| 62 | for i, u := range vv { |
| 63 | fmt.Println(i, u) |
| 64 | } |
| 65 | default: |
| 66 | fmt.Println(k, "is of a type I don't know how to handle") |
| 67 | } |
| 68 | } |
| 69 | |
| 70 | // STOP OMIT |
| 71 | } |
| 72 | |
| 73 | func main() { |
| 74 | Decode() |
| 75 | } |