【问题标题】:How to convert Enlive Object to JSON Object in Clojure?如何在 Clojure 中将 Enlive 对象转换为 JSON 对象?
【发布时间】:2021-05-07 06:45:17
【问题描述】:

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

我使用下面的解析方法解析了一个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}}
}

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

我在执行此转换步骤时遇到了问题。提前感谢您的帮助。

【问题讨论】:

  • 你的目标对象是一个 Clojure 嵌套映射;它不是 JSON 字符串(即您没有任何双引号)。此外,键都是 Clojure 关键字,而不是 JSON 字典键(字符串)。
  • 请添加您尝试过的代码以及失败的原因(例如错误、堆栈跟踪、日志等),以便我们对其进行改进。
  • stackoverflow.com/questions/66016572/… 中,您要求创建 EDN(但您的示例在技术上是 EDN,但看起来更像 YAML 的 CLJ 版本)。现在您要的是 JSON,但您的示例是 EDN。上述链接的答案提供了一种构建您在此处要求的确切结果的方法。您的实际问题是如何将 EDN 转换为 JSON?

标签: json object clojure type-conversion enlive


【解决方案1】:

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

(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"}}}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 2017-06-16
    • 1970-01-01
    • 2017-07-29
    • 2022-01-24
    • 2016-04-24
    相关资源
    最近更新 更多