I need need to transform a JSON payload into XML. Would you use a library like Jackson for this or write it yourself in Clojure? (code in thread)
(ns data-to-xml
(:require [clojure.data.xml :as xml]))
(defn edn->xml
[k v]
(cond
(map? v)
(xml/element k {}
(map (fn [[sub-k sub-v]]
(edn->xml sub-k sub-v))
v))
(sequential? v)
(map (fn [item]
(edn->xml k item))
v)
:else
(xml/element k {} (str v))))
(defn data->xml
[root-tag data]
(xml/element root-tag {}
(mapcat (fn [[k v]]
(let [result (edn->xml k v)]
(if (sequential? result)
result ; Already returns multiple elements
[result]))) ; Wrap single element in vector
data)))
(defn edn->xml-str
[root-tag data]
(xml/emit-str (data->xml root-tag data)))
Pretty straightforward code without any edge case handling. But the JSON payloads are pretty uniform and small (double digit kb).Unless you have other concerns, like e.g. the utmost performance or some advanced XML features, I'd choose clojure.data stuff.
Jackson is a PITA.
Thatβs what I was hoping, thank you π