I'm working on representing an API where a response contains a hash where the keys are of type String and the values can be of any type. Is there a way to represent this in Crystal?
I did not see a way to represent this looking through Crystal docs on types:
- https://crystal-lang.org/reference/1.6/syntax_and_semantics/literals/index.html
- https://crystal-lang.org/reference/1.6/syntax_and_semantics/literals/hash.html
In OpenAPI Spec, this is described as a free-form object:
https://swagger.io/docs/specification/data-models/dictionaries/#free-form
Free-Form Objects
If the dictionary values can be of any type (aka free-form object), use additionalProperties: true:
type: objectadditionalProperties: trueThis is equivalent to:
type: objectadditionalProperties: {}
In Go, this would be represented as map[string]any or map[string]interface{}.
Given that everything is an object in Crystal, the following compiles for me:
Hash(String, Object)Ref: https://crystal-lang.org/reference/1.6/syntax_and_semantics/everything_is_an_object.html
Ref: https://crystal-lang.org/api/1.8.2/Object.html