clojure.data.json写入/读取会影响活动数据

时间:2015-01-23 10:56:21

标签: json clojure enlive

保存和重新加载enlive的{​​{1}}输出的json方法是什么。

以下过程不保留数据结构(请注意,我要求json / read-str将键映射到符号):

html-resource

感谢。

更新

要解答Mark Fischer的评论,我发布了一个代表(require net.cgrand.enlive-html :as html) (require clojure.data.json :as json) (def craig-home (html/html-resource (java.net.URL. "http://www.craigslist.org/about/sites"))) (spit "./data/test_json_flow.json" (json/write-str craig-home)) (def craig-reloaded (json/read-str (slurp "./data/test_json_flow.json") :key-fn keyword)) (defn count-nodes [page] (count (html/select page [:div.box :h4]))) (println (count-nodes craig-home)) ;; => 140 (println (count-nodes craig-reloaded)) ;; => 0 代替html/select的其他代码

html/html-resource

1 个答案:

答案 0 :(得分:1)

更简单的方法是使用Clojure edn进行写/读:

(require '[net.cgrand.enlive-html :as html])
(require '[clojure.data.json :as json])

(def craig-home (html/html-resource (java.net.URL. "http://www.craigslist.org/about/sites")))

(spit "./data/test_json_flow.json" (pr-str craig-home))

(def craig-reloaded
  (clojure.edn/read-string (slurp "./data/test_json_flow.json")))

(defn count-nodes [page] (count (html/select page [:div.box :h4])))
(println (count-nodes craig-home)) ;=>140
(println (count-nodes craig-reloaded)) ;=>140

Enlive期望标记名称值也是一个关键字,如果标记名称值是一个字符串(这是json / write-str和json / read-str将关键字转换为),则不会找到节点。

(json/write-str '({:tag :h4, :attrs nil, :content ("Illinois")}))
;=> "[{\"tag\":\"h4,\",\"attrs\":null,\"content\":[\"Illinois\"]}]"

(json/read-str (json/write-str '({:tag :h4, :attrs nil, :content ("Illinois")})) :key-fn keyword)
;=> [{:tag "h4", :attrs nil, :content ["Illinois"]}]

(pr-str '({:tag :h4 :attrs nil :content ("Illinois")}))
;=> "({:tag :h4, :attrs nil, :content (\"Illinois\")})"

(clojure.edn/read-string (pr-str '({:tag :h4, :attrs nil, :content ("Illinois")})))
;=> ({:tag :h4, :attrs nil, :content ("Illinois")})

如果必须使用json,则可以使用以下命令将:tag值转换为关键字:

(clojure.walk/postwalk #(if-let [v (and (map? %) (:tag %))]
                          (assoc % :tag (keyword v)) %)
                       craig-reloaded)