nesting.go 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. /*
  2. * Public Domain Software
  3. *
  4. * I (Matthias Ladkau) am the author of the source code in this file.
  5. * I have placed the source code in this file in the public domain.
  6. *
  7. * For further information see: http://creativecommons.org/publicdomain/zero/1.0/
  8. */
  9. package datautil
  10. import "fmt"
  11. /*
  12. GetNestedValue gets a value from a nested object structure.
  13. */
  14. func GetNestedValue(d map[string]interface{}, path []string) (interface{}, error) {
  15. var ret interface{}
  16. var err error
  17. getNestedMap := func(d map[string]interface{}, key string) (map[string]interface{}, error) {
  18. val := d[key]
  19. newMap, ok := val.(map[string]interface{})
  20. if !ok {
  21. return nil, fmt.Errorf("Unexpected data type %T as value of %v", val, key)
  22. }
  23. return newMap, nil
  24. }
  25. // Drill into the object structure and return the requested value.
  26. nestedMap := d
  27. atomLevel := len(path) - 1
  28. for i, elem := range path {
  29. if i < atomLevel {
  30. if nestedMap, err = getNestedMap(nestedMap, elem); err != nil {
  31. break
  32. }
  33. } else {
  34. ret = nestedMap[elem]
  35. }
  36. }
  37. return ret, err
  38. }