在Crystal语言中,JSON::Any和JSON::Type有什么区别?这种类型的用例有哪些?
JSON :: Type是递归定义的“别名”:
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是一个Struct(Struct <Value <Object); JSON :: Any的实例保存任何JSON类型的“原始”值:
cr(0.24.1) > x=JSON::Any.new("hi") => "hi" icr(0.24.1) > x => "hi" icr(0.24.1) > x.raw => "hi"
JSON :: Any is a struct,由于解析而返回 . 它有方便的方法来访问底层数据 as_s , as_bool , as_f 等:
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 struct内部用于represent the data:
JSON::Type
JSON::Any
p obj.raw # => {"access" => true} p obj.raw.class # => Hash(String, JSON::Type)
2 回答
JSON :: Type是递归定义的“别名”:
别名是Crystal的类型语法的一部分 . 有关详细信息,请参阅https://crystal-lang.org/docs/syntax_and_semantics/alias.html
JSON :: Any是一个Struct(Struct <Value <Object); JSON :: Any的实例保存任何JSON类型的“原始”值:
JSON :: Any is a struct,由于解析而返回 . 它有方便的方法来访问底层数据
as_s
,as_bool
,as_f
等:JSON::Type
是所有可能的json类型的联合类型 . 它由JSON::Any
struct内部用于represent the data: