0

enlivehtml-resource出力を保存してリロードするための適切な json の方法は何ですか。

次の手順では、データ構造が保持されません (キーをシンボルにマップするように json/read-str に指示していることに注意してください)。

(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

ありがとう。

アップデート

Mark Fischer のコメントに対処するためhtml/selectに、代わりに対処する別のコードを投稿しますhtml/html-resource

(def craig-home
  (html/html-resource (java.net.URL. "http://www.craigslist.org/about/sites")))
(def craig-boxes (html/select craig-home [:div.box]))
(count (html/select craig-boxes [:h4])) ;; => 140

(spit "./data/test_json_flow.json" (json/write-str  craig-boxes))
(def craig-boxes-reloaded
  (json/read-str (slurp "./data/test_json_flow.json") :key-fn keyword))
(count (html/select craig-boxes-reloaded [:h4])) ;; => 0
4

1 に答える 1

2

より簡単なアプローチは、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)
于 2015-01-23T12:50:56.613 に答える