0

我对 Clojure 有点陌生,想知道如何将这个 Enlive 对象转换为 JSON 对象。

我使用下面的 parse 方法解析了一个 XML 文件:

(def xml-parser
  (parse "<Vehicle><Model>Toyota</Model><Color>Red</Color><Loans><Reoccuring>Monthly</Reoccuring><Owners><Owner>Bob</Owner></Owners></Loans><Tires><Model>123123</Model><Size>23</Size></Tires><Engine><Model>30065</Model></Engine></Vehicle>"))

并像这样获得了一个 Enlive 对象:

{:tag :Vehicle,
 :attrs nil,
 :content
 [{:tag :Model, :attrs nil, :content ["Toyota"]}
  {:tag :Color, :attrs nil, :content ["Red"]}
  {:tag :Loans,
   :attrs nil,
   :content
   [{:tag :Reoccuring, :attrs nil, :content ["Monthly"]}
    {:tag :Owners,
     :attrs nil,
     :content [{:tag :Owner, :attrs nil, :content ["Bob"]}]}]}
  {:tag :Tires,
   :attrs nil,
   :content
   [{:tag :Model, :attrs nil, :content ["123123"]}
    {:tag :Size, :attrs nil, :content ["23"]}]}
  {:tag :Engine,
   :attrs nil,
   :content [{:tag :Model, :attrs nil, :content ["30065"]}]}]}

我希望能够将其转换为 JSON 对象,如下所示:

{:Vehicle {:Model "Toyota"
           :Color "Red"
           :Loans {:Reoccuring "Monthly"
                   :Owners {:Owner "Bob"}}
           :Tires {
                   :Model 123123
                   :Size 23}
           :Engine {:Model 30065}}
}

如果使用的词汇不完全准确,我深表歉意

我在这一步转换时遇到了麻烦。提前谢谢你的帮助。

4

1 回答 1

2

这应该和递归内容转换一样简单:

(defn process-rec [{:keys [tag content]}]
  {tag (if (string? (first content))
         (first content)
         (apply merge (map process-rec content)))})

或者像这样,进行更深层次的解构:

(defn process-rec [{tag :tag [x :as content] :content}]
  {tag (if (string? x) x (into {} (map process-rec) content))})

例子:

user> (process-rec data)
;;=> {:Vehicle
;;    {:Model "Toyota",
;;     :Color "Red",
;;     :Loans {:Reoccuring "Monthly", :Owners {:Owner "Bob"}},
;;     :Tires {:Model "123123", :Size "23"},
;;     :Engine {:Model "30065"}}}
于 2021-02-03T13:08:16.683 回答