-
Notifications
You must be signed in to change notification settings - Fork 0
/
jsonvalidation.clj
41 lines (37 loc) · 1.56 KB
/
jsonvalidation.clj
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
(ns protean.api.transformation.jsonvalidation
"Tools for validating json/xml."
(:import [com.fasterxml.jackson.databind ObjectMapper]
[com.github.fge.jsonschema.main JsonSchemaFactory]))
(def
^{:private true
:doc "An immutable and therefore thread-safe JSON schema factory.
You can call (.getJsonSchema json-schema-factory <json-schema-node>)
to retrieve a JsonSchema instance which can validate JSON."}
json-schema-factory
(JsonSchemaFactory/byDefault))
(def
^{:private true
:doc "Initialize the object mapper first and keep it private as not all
of its methods are thread-safe. Optionally configure it here.
Reader instances are cheap to create."}
object-reader
(let [object-mapper (ObjectMapper.)]
(fn [] (.reader object-mapper))))
(defn- parse-to-node
"Parse the given String as JSON. Returns a Jackson JsonNode."
[data]
(-> (object-reader) (.readTree data)))
(defn validate
"Validates the given 'data' against the JSON schema. Returns an object
with an :success property that equals true when the schema could
successfully be validated. It additionally contains a :message property
with a human readable error description."
[schema data]
(try
(let [parsed-schema (parse-to-node (slurp schema))
schema (-> json-schema-factory (.getJsonSchema parsed-schema))
parsed-data (parse-to-node data)
report (.validate schema parsed-data)]
{:success (.isSuccess report)
:message (str report)})
(catch Exception e {:success false :message (.getMessage e)})))