-1

Clojure Prismatic スキーマの検証に問題があります。これがコードです。

: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に非常に慣れていませんが、まだその基本を学ぼうとしています。

ありがとう、

4

1 に答える 1

3

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"}}})

それが役立つことを願っています。

于 2016-05-17T03:14:31.827 に答える