Skip to content

Commit

Permalink
Merge pull request #577 from MUzairS15/MUzairS15/utils
Browse files Browse the repository at this point in the history
add helper functions for casting
  • Loading branch information
Mohd Uzair authored Aug 22, 2024
2 parents 9c6bfaf + 3a32a2a commit d63c8af
Showing 1 changed file with 43 additions and 0 deletions.
43 changes: 43 additions & 0 deletions utils/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -452,3 +452,46 @@ func FindEntityType(content []byte) (entity.EntityType, error) {
}
return "", ErrInvalidSchemaVersion
}

// RecursiveCastMapStringInterfaceToMapStringInterface will convert a
// map[string]interface{} recursively => map[string]interface{}
func RecursiveCastMapStringInterfaceToMapStringInterface(in map[string]interface{}) map[string]interface{} {
res := ConvertMapInterfaceMapString(in)
out, ok := res.(map[string]interface{})
if !ok {
fmt.Println("failed to cast")
}

return out
}

// ConvertMapInterfaceMapString converts map[interface{}]interface{} => map[string]interface{}
//
// It will also convert []interface{} => []string
func ConvertMapInterfaceMapString(v interface{}) interface{} {
switch x := v.(type) {
case map[interface{}]interface{}:
m := map[string]interface{}{}
for k, v2 := range x {
switch k2 := k.(type) {
case string:
m[k2] = ConvertMapInterfaceMapString(v2)
default:
m[fmt.Sprint(k)] = ConvertMapInterfaceMapString(v2)
}
}
v = m

case []interface{}:
for i, v2 := range x {
x[i] = ConvertMapInterfaceMapString(v2)
}

case map[string]interface{}:
for k, v2 := range x {
x[k] = ConvertMapInterfaceMapString(v2)
}
}

return v
}

0 comments on commit d63c8af

Please sign in to comment.