在clojure中加载配置文件作为数据结构 [英] loading configuration file in clojure as data structure
问题描述
在clojure中有解析clojure数据结构的阅读器函数吗?我的用例是读取配置属性文件,一个属性的值应该是一个列表。我想将其写成:
file.properties:
property1 = [value1value2]
p>
(load-propsfile.properties)
并获取值为{property1,[value1value2]的映射
现在,使用相同的输入文件file.properties执行以下操作:
(defn load-props [filename]
(let [io(java.io.FileInputStream。filename)
prop(java.util.Properties。)]
(.load prop io)
(into {} prop)
;;返回:
;; {property1[\valu1\,\valu2\]}
(load-propsfile.properties)
但我不能得到一个方法来解析结果到clojure的向量。我基本上寻找像Erlang的文件:咨询/ 1函数。
java.util.Properties
任何想法如何做到这一点?
implements Map
,这样可以非常容易地完成,无需手动解析属性文件:
(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 {} ]
(load-propstest.properties)
; => {:property3 {:foo 100,:bar:test},:property2 99.9,:property1 [foobar]}
$ b b
特别是,属性文件比你想象的更复杂(注释,转义等等)和 java.util.Properties
是非常好的在加载它们。
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'd like to be able to write this as:
file.properties:
property1 = ["value1" "value2"]
and in clojure:
(load-props "file.properties")
and get a map with value {property1, ["value1" "value2"]
Right now,m I'm doing the following, with the same input file "file.properties":
(defn load-props [filename]
(let [io (java.io.FileInputStream. filename)
prop (java.util.Properties.)]
(.load prop io)
(into {} prop)))
;; returns:
;; {"property1" "[\"valu1\", \"valu2\"]"}
(load-props "file.properties")
But I cannot get a way to parse the result to a clojure's vector. I'm basically looking for something like Erlang's file:consult/1 function. Any idea how to do this?
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.
这篇关于在clojure中加载配置文件作为数据结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!