简体   繁体   English

Namespaced关键字使JSON规范无效

[英]Namespaced keyword makes spec for JSON invalid

I am using Clojure.spec to validate the structure of JSON (and later conform it into another format): 我正在使用Clojure.spec来验证JSON的结构(后来将其符合另一种格式):

(s/def ::yes string?)
(s/def ::my-test (s/keys :req [::yes]))

(def my-json (json/read-json "{\"yes\": \"yes\"}")) ; => {:yes "yes"}

(s/valid? ::my-test my-json)       ; => false
(s/valid? ::my-test {::yes "yes"}) ; => true

(s/explain ::my-test {:yes "yes"})
; => val: {:yes "yes"} fails spec: :spec.core/my-test predicate: 
;         (contains? % :spec.core/yes)

(Here s refers to the clojure.spec namespace and json to clojure.data.json .) (这里的s指的是clojure.spec命名空间, json指的是clojure.data.json 。)

As can be seen above the s/valid? 从上面可以看出s/valid? fails for the parsed JSON because the keywords are not namespaced. 对于解析的JSON失败,因为关键字未命名空间。

How can I adjust the code so that the JSON is seen as valid? 如何调整代码以使JSON被视为有效?

You can do the following which will work: 您可以执行以下操作:

(def my-json (json/read-str "{\"yes\": \"yes\"}" :key-fn #(keyword (str *ns*) %)))

I'm not sure if this is the right/idiomatic way to handle it - I guess it depends on the case. 我不确定这是否是正确/惯用的方式来处理它 - 我想这取决于具体情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM