Crystal中的JSON::Any和JSON::Type有什么区别?
What is the difference between JSON::Any and JSON::Type in Crystal?
在Crystal语言中,JSON::Any and JSON::Type有什么区别?这种类型的用例是什么?
JSON::Any is a struct,作为解析的结果返回。它有方便的方法来访问基础数据 as_s
、as_bool
、as_f
等。:
obj = JSON.parse %({"access": true})
p obj.class # => JSON::Any
p obj["access"] # => true
p obj["access"].class # => JSON::Any
JSON::Type
是所有可能的 json 类型的联合类型。它由 JSON::Any
结构内部使用到 represent the data:
p obj.raw # => {"access" => true}
p obj.raw.class # => Hash(String, JSON::Type)
JSON::Type 是递归定义的 "alias":
alias Type = Nil | Bool | Int64 | Float64 | String | Array(Type) | Hash(String, Type)
别名是 Crystal 类型语法的一部分。详情见https://crystal-lang.org/docs/syntax_and_semantics/alias.html
JSON::Any 是一个结构体(结构体 < 值 < 对象); JSON::Any 的实例包含任何 JSON 类型的 "raw" 值:
cr(0.24.1) > x=JSON::Any.new("hi")
=> "hi"
icr(0.24.1) > x
=> "hi"
icr(0.24.1) > x.raw
=> "hi"
在Crystal语言中,JSON::Any and JSON::Type有什么区别?这种类型的用例是什么?
JSON::Any is a struct,作为解析的结果返回。它有方便的方法来访问基础数据 as_s
、as_bool
、as_f
等。:
obj = JSON.parse %({"access": true})
p obj.class # => JSON::Any
p obj["access"] # => true
p obj["access"].class # => JSON::Any
JSON::Type
是所有可能的 json 类型的联合类型。它由 JSON::Any
结构内部使用到 represent the data:
p obj.raw # => {"access" => true}
p obj.raw.class # => Hash(String, JSON::Type)
JSON::Type 是递归定义的 "alias":
alias Type = Nil | Bool | Int64 | Float64 | String | Array(Type) | Hash(String, Type)
别名是 Crystal 类型语法的一部分。详情见https://crystal-lang.org/docs/syntax_and_semantics/alias.html
JSON::Any 是一个结构体(结构体 < 值 < 对象); JSON::Any 的实例包含任何 JSON 类型的 "raw" 值:
cr(0.24.1) > x=JSON::Any.new("hi")
=> "hi"
icr(0.24.1) > x
=> "hi"
icr(0.24.1) > x.raw
=> "hi"