json3.go 1.2 KB

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