maputils.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package maputils
  2. import (
  3. "errors"
  4. "strconv"
  5. "strings"
  6. )
  7. const (
  8. pathSeparator = "."
  9. )
  10. func FindValueInMap(find map[string]any, path string) (any, error) {
  11. if find == nil || strings.TrimSpace(path) == "" {
  12. return nil, errors.New("没有传递需要查找的数据或路径")
  13. }
  14. var retValue any
  15. var currentFind any
  16. currentFind = find
  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. }