12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273 |
- package maputils
- import (
- "errors"
- "strconv"
- "strings"
- )
- const (
- pathSeparator = "."
- )
- func FindValueInMap(find map[string]any, path string) (any, error) {
- if find == nil || strings.TrimSpace(path) == "" {
- return nil, errors.New("没有传递需要查找的数据或路径")
- }
- var retValue any
- var currentFind any
- currentFind = find
- pathParts := strings.Split(path, pathSeparator)
- for _, pathPart := range pathParts {
- if strings.HasPrefix(pathPart, "[") && strings.HasSuffix(pathPart, "]") {
- indexStr := strings.TrimLeft(strings.TrimRight(pathPart, "]"), "[")
- index, err := strconv.Atoi(strings.Trim(indexStr, " "))
- if err != nil {
- return nil, err
- }
- findSlice, ok := currentFind.([]any)
- if ok {
- if index > len(findSlice)-1 {
- retValue = nil
- } else {
- retValue = findSlice[index]
- }
- } else {
- findMapSlice, ok := currentFind.([]map[string]any)
- if !ok {
- return nil, errors.New("对应slice路径的值不是slice: " + pathPart)
- }
- if index > len(findMapSlice)-1 {
- retValue = nil
- } else {
- retValue = findMapSlice[index]
- }
- }
- } else {
- findMap, ok := currentFind.(map[string]any)
- if !ok {
- return nil, errors.New("对应map路径的值不是map: " + pathPart)
- }
- value, ok := findMap[pathPart]
- if !ok {
- return nil, nil
- }
- retValue = value
- }
- if retValue == nil {
- return nil, nil
- }
- currentFind = retValue
- }
- return retValue, nil
- }
|