convertToStringKeysRecursive ensures keys are converted to strings for jsonschema.
(value interface{}, keyPrefix string)
| 44 | |
| 45 | // convertToStringKeysRecursive ensures keys are converted to strings for jsonschema. |
| 46 | func convertToStringKeysRecursive(value interface{}, keyPrefix string) (interface{}, error) { |
| 47 | if mapping, ok := value.(map[string]interface{}); ok { |
| 48 | dict := make(map[string]interface{}) |
| 49 | for str, entry := range mapping { |
| 50 | var newKeyPrefix string |
| 51 | if keyPrefix == "" { |
| 52 | newKeyPrefix = str |
| 53 | } else { |
| 54 | newKeyPrefix = fmt.Sprintf("%s.%s", keyPrefix, str) |
| 55 | } |
| 56 | convertedEntry, err := convertToStringKeysRecursive(entry, newKeyPrefix) |
| 57 | if err != nil { |
| 58 | return nil, err |
| 59 | } |
| 60 | dict[str] = convertedEntry |
| 61 | } |
| 62 | return dict, nil |
| 63 | } |
| 64 | if mapping, ok := value.(map[interface{}]interface{}); ok { |
| 65 | dict := make(map[string]interface{}) |
| 66 | for key, entry := range mapping { |
| 67 | str, ok := key.(string) |
| 68 | if !ok { |
| 69 | return nil, formatInvalidKeyError(keyPrefix, key) |
| 70 | } |
| 71 | var newKeyPrefix string |
| 72 | if keyPrefix == "" { |
| 73 | newKeyPrefix = str |
| 74 | } else { |
| 75 | newKeyPrefix = fmt.Sprintf("%s.%s", keyPrefix, str) |
| 76 | } |
| 77 | convertedEntry, err := convertToStringKeysRecursive(entry, newKeyPrefix) |
| 78 | if err != nil { |
| 79 | return nil, err |
| 80 | } |
| 81 | dict[str] = convertedEntry |
| 82 | } |
| 83 | return dict, nil |
| 84 | } |
| 85 | if list, ok := value.([]interface{}); ok { |
| 86 | var convertedList []interface{} |
| 87 | for index, entry := range list { |
| 88 | newKeyPrefix := fmt.Sprintf("%s[%d]", keyPrefix, index) |
| 89 | convertedEntry, err := convertToStringKeysRecursive(entry, newKeyPrefix) |
| 90 | if err != nil { |
| 91 | return nil, err |
| 92 | } |
| 93 | convertedList = append(convertedList, convertedEntry) |
| 94 | } |
| 95 | return convertedList, nil |
| 96 | } |
| 97 | return value, nil |
| 98 | } |
| 99 | |
| 100 | func formatInvalidKeyError(keyPrefix string, key interface{}) error { |
| 101 | var location string |
no test coverage detected