0

Is there a way to instruct clojure.core.edn/read how to resolve auto namespaced keywords ?

  (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

The last exception makes sense, since "A keyword cannot begin with ::".

I could use load-file with this simple example, however I also need the extensibility of edn (read custom tags).

Having a parameter to instruct how to resolve namespaces would make my config files (coerced with clojure.spec) much more readable.

nha
  • 17,623
  • 13
  • 87
  • 133
  • 1
    Have you tried using `clojure.core/read-string`? – OlegTheCat Jul 26 '16 at 15:56
  • @OlegTheCat interesting, I did not ! I have to dig in it's options map though. – nha Jul 26 '16 at 15:57
  • @OlegTheCat so as far as I understand it now, clojure.core/read-string will not allow me to have readers like in edn. This will prevent me from having configuations defined as in https://github.com/juxt/aero (could have worked otherwise). – nha Jul 26 '16 at 16:20
  • 1
    @nha Perhaps [`tools.reader`](https://github.com/clojure/tools.reader) can do what you need? I haven't used it myself, though, so I could be wrong. – Sam Estep Jul 26 '16 at 16:42

2 Answers2

0

So in my case it turn out the simplest solution is to use clojure.spec with un-namespaced keywords in my config file (I did not know it could do that).

Using the core readers functions would have worked too.

Quote from Alex Miller on 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

nha
  • 17,623
  • 13
  • 87
  • 133
0

I like to transform the string before parsing it in order to keep the edn files clean without having to treat the spec keys as unqualified.

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

This may not be very robust when writing and re-reading edn files, but it works nicely for configuration data.

mahercbeaucoup
  • 597
  • 5
  • 15