Clojure edn 读取自动命名空间关键字

Clojure edn read auto namespaced keywords

有没有办法指示 clojure.core.edn/read 如何解析自动命名空间关键字?

  (edn/read-string "{:not-namespaced \"ko\" }") ;;=> {:not-namespaced "ko"}
  (edn/read-string "{:namespaced/ok \"ko\" }")  ;;=> #:namespaced{:ok "ko"}
  (edn/read-string "{::namespaced \"ko\" }")    ;;=> Unhandled java.lang.RuntimeException Invalid token: ::namespaced autonamespaced does not work

最后一个例外是有道理的,因为 "A keyword cannot begin with ::"

我可以在这个简单的示例中使用 load-file,但是我还需要 edn 的可扩展性(读取自定义标签)。

有一个参数来指示如何解析命名空间将使我的配置文件(用 clojure.spec 强制)更具可读性。

所以在我的例子中,最简单的解决方案是在我的配置文件中使用 clojure.spec 和未命名空间的关键字(我不知道它可以这样做)。

使用核心阅读器功能也可以。

Alex Miller 在 slack 上的引述:

Yes, you'll need full namespaces in edn config files You could also write specs on unqualified keys with req-un and opt-un

Either the normal core reader fns or clojure.edn reader fns should be able to read tagged literals though with # You just need to bind around the call to set up the readers

我喜欢在解析字符串之前对其进行转换,以便保持 edn 文件的清洁,而不必将规范键视为不合格。

(-> "{::namespaced \"ko\" }"
    (#(string/replace % #"::" ":some.namespace/"))
    (edn/read-string))

这在写入和重新读取 edn 文件时可能不是很稳健,但它对配置数据非常有效。