rewrite-clj

pavlosmelissinos 2022-11-04T18:22:57.869329Z

Hello ๐Ÿ™‚ How do I mimic "clojure.core/filter" & first with rewrite-clj? Searched the docs but couldn't find the answer. Context: I have an edn file that contains a vector and I want to replace the entry that contains a specific id. I'm pretty sure I can use rewrite-clj.zip/replace as soon as I identify the correct node but I'm having trouble finding it. Example in ๐Ÿงต

snoe 2022-11-07T16:58:02.474669Z

z/sexpr may be useful to you in the future, rather than comparing strings.

๐Ÿ‘ 1
borkdude 2022-11-07T16:59:15.522359Z

z/sexpr may blow up in your face sometimes though ;)

pavlosmelissinos 2022-11-07T18:57:38.944709Z

I'll look it up, thanks

pavlosmelissinos 2022-11-04T18:23:31.301229Z

(def content "[{:id :a :label \"foo\"}
               {:id :b :label \"bar\"}
               {:id :c :label \"baz\"}
               {:id :d :label \"bat\"}]")
(defn replace-entry [content id new-content]
    ,,,)
(replace-entry content :c {:id :c :label "bal" :organization "me"})

=> "[{:id :a :label \"foo\"}
     {:id :b :label \"bar\"}
     {:id :c :label \"bal\" :organization \"me\"}
     {:id :d :label \"bat\"}]"

borkdude 2022-11-04T18:24:39.961609Z

There may be something relevant in https://github.com/borkdude/rewrite-edn

borkdude 2022-11-04T18:25:10.676429Z

Not sure right away, but perhaps it might give you some inspiration

pavlosmelissinos 2022-11-04T18:25:31.524909Z

Thanks, I'll take a look ๐Ÿ™‚

borkdude 2022-11-04T18:26:24.157479Z

I think you could combine it at least to move to the map with the right id and then remove or replace it using a zipper operation

pavlosmelissinos 2022-11-04T22:12:08.484449Z

In case anyone is interested, this is the closest I came up with...

(defn filterz [zloc f] (z/find zloc #(->> % z/string f)))

  (defn replace-entry [content id new-content]
    (-> (z/of-string content)
        z/down
        (filterz #(= (:id (clojure.edn/read-string %)) id))
        (z/replace new-content)
        z/root-string))
I think it's good enough for now ๐Ÿ˜„

๐Ÿ‘ 2