example.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package main
  2. import (
  3. "fmt"
  4. "red-green/glom"
  5. )
  6. func main() {
  7. // An example structure (Shown using all maps, but slice/array and even structures are supported)
  8. critters := make(map[string]interface{})
  9. cat := make(map[string]interface{})
  10. cat["name"] = "Cat"
  11. cat["sounds"] = "Meow"
  12. cat["food"] = "Fish"
  13. critters["Cat"] = cat
  14. dog := make(map[string]interface{})
  15. dog["name"] = "Dog"
  16. dog["sounds"] = "Woof"
  17. dog["food"] = "Anything"
  18. critters["Dog"] = dog
  19. test := make(map[string]interface{})
  20. test["Animals"] = critters
  21. /* In JSON it would be represented as:
  22. {
  23. "Animals": {
  24. "Cat": {
  25. "name": "Cat",
  26. "sounds": "Meow",
  27. "food": "Fish"
  28. },
  29. "Dog": {
  30. "name": "Dog",
  31. "sounds": "Woof",
  32. "food": "Anything"
  33. }
  34. }
  35. }
  36. Where accessing name would be
  37. data["Animals"]["Cat"]["name"] or data["Animals"]["Dog"]["name"]
  38. But with glom-go it's
  39. "Animals.Cat.name" or "Animals.Dog.name"
  40. */
  41. // An example of accessing something that doesn't exist
  42. _, err := glom.Glom(test, "Animals.Dog.hates")
  43. if err != nil {
  44. fmt.Println(err) // Failed moving to 'hates' from path of 'Animals.Dog', options are 'name', 'sounds', 'food' (3)
  45. }
  46. // An example of successfully geting something
  47. value, err := glom.Glom(test, "Animals.Cat.sounds")
  48. if err != nil {
  49. fmt.Println(err)
  50. } else {
  51. fmt.Printf("Cat's make '%v' sounds.\r\n", value)
  52. }
  53. }