Reputation: 2149
In Crystal language, what is the difference between JSON::Any and JSON::Type? What are the use cases of this types?
Upvotes: 3
Views: 426
Reputation: 116720
JSON::Type is a recursively-defined "alias":
alias Type = Nil | Bool | Int64 | Float64 | String | Array(Type) | Hash(String, Type)
Aliases are part of Crystal's type grammar. For details, see https://crystal-lang.org/docs/syntax_and_semantics/alias.html
JSON::Any is a Struct (Struct < Value < Object); an instance of JSON::Any holds the "raw" value of any JSON type:
cr(0.24.1) > x=JSON::Any.new("hi")
=> "hi"
icr(0.24.1) > x
=> "hi"
icr(0.24.1) > x.raw
=> "hi"
Upvotes: 2
Reputation: 7326
JSON::Any is a struct, which is returned as a result of parsing. It has convenient methods to access underlying data as_s
, as_bool
, as_f
etc. :
obj = JSON.parse %({"access": true})
p obj.class # => JSON::Any
p obj["access"] # => true
p obj["access"].class # => JSON::Any
JSON::Type
is an union type of all possible json types. It is used internally by JSON::Any
struct to represent the data:
p obj.raw # => {"access" => true}
p obj.raw.class # => Hash(String, JSON::Type)
Upvotes: 5