loading configuration file in clojure as data structure

前端 未结 5 1970
小鲜肉
小鲜肉 2020-12-24 12:10

Is there a reader function in clojure to parse clojure data structure? My use case is to read configuration properties files and one value for a property should be a list. I

5条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-24 12:31

    java.util.Properties implements Map so this can be done very easily without manually parsing properties files:

    (require 'clojure.java.io)
    (defn load-props
      [file-name]
      (with-open [^java.io.Reader reader (clojure.java.io/reader file-name)] 
        (let [props (java.util.Properties.)]
          (.load props reader)
          (into {} (for [[k v] props] [(keyword k) (read-string v)])))))
    
    (load-props "test.properties")
    ;=> {:property3 {:foo 100, :bar :test}, :property2 99.9, :property1 ["foo" "bar"]}
    

    In particular, properties files are more complicated than you think (comments, escaping, etc, etc) and java.util.Properties is very good at loading them.

提交回复
热议问题