maputils.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package maputils
  2. import (
  3. "errors"
  4. "strconv"
  5. "strings"
  6. )
  7. const (
  8. pathSeparator = "."
  9. )
  10. func GetValueByPath(m map[string]any, path string) (any, error) {
  11. if m == nil || strings.TrimSpace(path) == "" {
  12. return nil, errors.New("没有传递需要查找的数据或路径")
  13. }
  14. var retValue any
  15. var currentFind any
  16. currentFind = m
  17. pathParts := strings.Split(path, pathSeparator)
  18. for _, pathPart := range pathParts {
  19. if strings.HasPrefix(pathPart, "[") && strings.HasSuffix(pathPart, "]") {
  20. indexStr := strings.TrimLeft(strings.TrimRight(pathPart, "]"), "[")
  21. index, err := strconv.Atoi(strings.Trim(indexStr, " "))
  22. if err != nil {
  23. return nil, err
  24. }
  25. findSlice, ok := currentFind.([]any)
  26. if ok {
  27. if index > len(findSlice)-1 {
  28. retValue = nil
  29. } else {
  30. retValue = findSlice[index]
  31. }
  32. } else {
  33. findMapSlice, ok := currentFind.([]map[string]any)
  34. if !ok {
  35. return nil, errors.New("对应slice路径的值不是slice: " + pathPart)
  36. }
  37. if index > len(findMapSlice)-1 {
  38. retValue = nil
  39. } else {
  40. retValue = findMapSlice[index]
  41. }
  42. }
  43. } else {
  44. findMap, ok := currentFind.(map[string]any)
  45. if !ok {
  46. return nil, errors.New("对应map路径的值不是map: " + pathPart)
  47. }
  48. value, ok := findMap[pathPart]
  49. if !ok {
  50. return nil, nil
  51. }
  52. retValue = value
  53. }
  54. if retValue == nil {
  55. return nil, nil
  56. }
  57. currentFind = retValue
  58. }
  59. return retValue, nil
  60. }
  61. func GetValueByKey[K comparable, V any](m map[K]any, key K) (V, bool) {
  62. var zeroValue V
  63. mapValue, ok := m[key]
  64. if !ok {
  65. return zeroValue, false
  66. }
  67. v, ok := mapValue.(V)
  68. if !ok {
  69. return zeroValue, false
  70. }
  71. return v, true
  72. }