Reputation: 8043
I have a text file consisting of a json value in each line. My file is as follows:
{"id":"a","family":"root","parent":nil,"value":"valueofa"}
{"id":"b1","family":"b","parent":"a","value":"valueofb1"}
{"id":"c1","family":"c","parent":"b1","value":"valueofc1"}
{"id":"c2","family":"c","parent":"b1","value":"valueofc2"}
{"id":"b2","family":"b","parent":"root","value":"valueofb2"}
{"id":"d1","family":"d","parent":"b1","value":"valueofd1"}
In the json given above, we the family attribute indicates a hierarchy, we would have "root" as the root,"b" as child of the "root","c" as child of "b" and and "d" would be child of "b" as well.
The idea is to iterate through the file and add the node being read at its proper place in a tree. One way would be to read these entries into a "map" and then use this map for any tree-manipulations. For any complex tree manipulations, I am not sure how this would work. It is quite possible that based on a certain requirement, I might have to detach a child from an existing parent and attach it to another parent. Apparently Clojure zippers are supposed to help in this regard but I am getting a little confused by how the hierarchy of nodes work in zippers.
It will be great if somebody could point me in the right direction here.
Upvotes: 2
Views: 775
Reputation: 26446
This is several questions, and probably too broad, but here's a sampling.
How do I read a file?
(def file-contents (slurp "foo.txt"))`
How do I convert JSON to Clojure data?
(require '[cheshire.core :refer [parse-string]])`
(def data (map #(parse-string % true)
(clojure.string/split file-contents #"\n")))
How do I treat a list with parent references like a tree?
(require '[clojure.zip :as z])
(defn create-zipper [s]
(let [g (group-by :parent s)]
(z/zipper g #(map :id (g %)) nil (-> nil g first :id))))
(def t (create-zipper data))
How do I use zippers?
user=> (-> t z/node)
"a"
user=> (-> t z/children)
("b1")
user=> (-> t z/down z/node)
"b1"
user=> (-> t z/down z/children)
("c1" "c2" "d1")
user=> (-> t z/down z/down z/rightmost z/node)
"d1"
Upvotes: 5