【问题标题】:validation of clojure schemaclojure 模式的验证
【发布时间】:2016-09-12 19:47:40
【问题描述】:

我在验证 clojure 棱柱模式时遇到问题。这是代码。

:Some_Var1 {:Some_Var2  s/Str
                  :Some_Var3 ( s/conditional
                        #(= "mytype1" (:type %)) s/Str
                        #(= "mytype2" (:type %)) s/Str
                  )}

我正在尝试使用代码验证它:

"Some_Var1": {
    "Some_Var2": "string",
"Some_Var3": {"mytype1":{"type":"string"}}
  }

但它给我一个错误:

{
  "errors": {
    "Some_Var1": {
      "Some_Var3": "(not (some-matching-condition? a-clojure.lang.PersistentArrayMap))"
    }
  }
}

这是我要验证的非常基本的代码。我对clojure很陌生,仍在尝试学习它的基础知识。

谢谢,

【问题讨论】:

    标签: if-statement clojure plumatic-schema


    【解决方案1】:

    欢迎使用 Clojure!这是一门很棒的语言。

    在 Clojure 中,关键字和字符串是不同的类型,即 :type"type" 不同。例如:

    user=> (:type  {"type" "string"})
    nil
    (:type  {:type "string"})
    "string"
    

    但是,我认为这里有一个更深层次的问题:通过查看您的数据,您似乎想要在数据本身中编码类型信息,然后根据该信息检查它。这可能是可能的,但这将是模式的非常高级的用法。当类型在类型之前已知时,通常使用模式,例如像这样的数据:

    (require '[schema.core :as s])
    (def data
      {:first-name "Bob"
       :address {:state "WA"
                 :city "Seattle"}})
    
    (def my-schema
      {:first-name s/Str
       :address {:state s/Str
                 :city s/Str}})
    
    (s/validate my-schema data)
    

    我建议,如果您需要基于编码的类型信息进行验证,那么为此编写一个自定义函数可能会更容易。

    希望有帮助!

    更新:

    conditional 工作原理的一个示例,这是一个将验证的架构,但同样,这是架构的非惯用用法:

    (s/validate
    {:some-var3
    (s/conditional
     ;; % is the value: {"mytype1" {"type" "string"}}
     ;; so if we want to check the "type", we need to first
     ;; access the "mytype1" key, then the "type" key
     #(= "string" (get-in % ["mytype1" "type"]))
     ;; if the above returns true, then the following schema will be used.
     ;; Here, I've just verified that
     ;; {"mytype1" {"type" "string"}}
     ;; is a map with key strings to any value, which isn't super useful
     {s/Str s/Any}
    )}
    {:some-var3 {"mytype1" {"type" "string"}}})
    

    希望对你有帮助。

    【讨论】:

    • 感谢您的回复,但我仍然无法解决问题。请你告诉我条件类型想要什么类型的结构化输入。如何在条件语句中选择 mytype1。
    • 使用conditional,每个子句都按顺序进行评估。在您的示例中, % 将具有值: {"mytype1" {"type" "string"}} 请注意,此值没有键 :type,即使有,:type 也映射到 "string"而不是"mytype"
    猜你喜欢
    • 2014-07-18
    • 1970-01-01
    • 2019-04-27
    • 2012-05-02
    • 2012-03-29
    • 2011-06-02
    • 2011-06-08
    • 2019-02-16
    • 2010-11-22
    相关资源
    最近更新 更多