0

Say I have a nested structure in Clojure e.g.

(def res [:S [:AB [:A "a"] [:B "b"]]])

but with nested metadata on each/ any of the vectors.

e.g.

(defn meta-tree [t]
  (if (sequential? t)
    (cons (meta t) (map meta-tree (next t)))
    t))

(meta-tree result)
;=> (#:instaparse.gll{:start-index 0, :end-index 2}
     (#:instaparse.gll{:start-index 0, :end-index 2}
      (#:instaparse.gll{:start-index 0, :end-index 1} "a")
      (#:instaparse.gll{:start-index 1, :end-index 2} "b")))

How could I write that structure to transit so that all the nested metadata is preserved, and can be read the other side?

judep
  • 85
  • 7

1 Answers1

3

Simply use t/write-meta

(set! *print-meta* true)

(def res
  ^#:instaparse.gll{:start-index 0, :end-index 2}
  [:S
   ^#:instaparse.gll{:start-index 0, :end-index 2}
   [:AB
    ^#:instaparse.gll{:start-index 0, :end-index 1}
    [:A "a"]
    ^#:instaparse.gll{:start-index 1, :end-index 2}
    [:B "b"]]])
res
#_#_=> 
^#:instaparse.gll{:start-index 0, :end-index 2}
[:S
 ^#:instaparse.gll{:start-index 0, :end-index 2}
 [:AB
  ^#:instaparse.gll{:start-index 0, :end-index 1}
  [:A "a"]
  ^#:instaparse.gll{:start-index 1, :end-index 2}
  [:B "b"]]]
(let [baos (ByteArrayOutputStream.)]
  (t/write (t/writer baos :json {:transform t/write-meta})
    res)
  (.flush baos)
  (t/read (t/reader (io/input-stream (.toByteArray baos)) :json)))
#_#_=> 
^#:instaparse.gll{:start-index 0, :end-index 2}
[:S
 ^#:instaparse.gll{:start-index 0, :end-index 2}
 [:AB
  ^#:instaparse.gll{:start-index 0, :end-index 1}
  [:A "a"]
  ^#:instaparse.gll{:start-index 1, :end-index 2}
  [:B "b"]]]

souenzzo
  • 359
  • 1
  • 6