我的问题可能有点容易回答,但我刚刚开始学习clojure,而且我不知道如何做到这一点。
我有一个我已阅读并解析过的JSON文件。现在我必须获取此JSON的每个元素,然后根据类型进行处理。 例如,我有JSON:
{
"foo": {
"id": 1,
"name": "foo1"
},
"bar": {
"id": 1,
"name": "bar1"
},
"foo": {
"id": 2,
"name": "foo2"
},
"bar": {
"id": 2,
"name": "bar2"
}
}
所以,我想创建一个迭代我的JSON的每个元素的函数,然后为我的JSON的每个元素类型调用另一个带有倍数声明的函数。
问题是我不知道如何获得JSON元素类型...... 有人能帮助我吗?
答案 0 :(得分:2)
您可以通过将其视为Clojure序列来获取地图的所有键值对。然后它表现为一个双元素向量序列,MapEntry
元素序列更精确。当您在first
上致电MapEntry
时,您将获得密钥。
所以(first (seq {:a 1}))
返回[:a 1]
,(first [:a 1])
返回:a
,即密钥。不需要在此示例中调用seq
,但只是为了使示例更加明确。
然后,您可以根据密钥编写case
表达式来执行操作。为了使其更具可扩展性,您可以使用多方法。
(def json-str "{\n \"foo\": {\n \"id\": 1,\n \"name\": \"foo1\"\n },\n \"bar\": {\n \"id\": 1,\n \"name\": \"bar1\"\n },\n \"foo\": {\n \"id\": 2,\n \"name\": \"foo2\"\n },\n \"bar\": {\n \"id\": 2,\n \"name\": \"bar2\"\n }\n}")
(def parsed (cheshire.core/parse-string json-str true))
;; {:foo {:id 2, :name "foo2"}, :bar {:id 2, :name "bar2"}}
;; handle with case:
(defn handle-data
[data]
(doseq [[k v] data]
(case k
:foo (println "this is a foo!" v)
:bar (println "this is a bar!" v)
(throw (ex-info (str "Did not recognize key "
key)
{:key k
:map v})))))
;; handle with multimethods:
(defmulti do-thing-depending-on-key first)
(defmethod do-thing-depending-on-key :foo [[k v]]
(println "this is a foo!" v))
(defmethod do-thing-depending-on-key :bar [[k v]]
(println "this is a bar!" k))
(defmethod do-thing-depending-on-key :default [[k v]]
(throw (ex-info (str "Did not recognize key "
key)
{:key k
:map v})))
(run! do-thing-depending-on-key parsed)
;; this is a foo! {:id 2, :name foo2}
;; this is a bar! {:id 2, :name bar2}
;; => nil
(run! do-thing-depending-on-key {:unknown {:id 3 :name "Unknown"}})
;; =>
;; clojure.lang.ExceptionInfo:
;; Did not recognize key :unknown {:key :unknown, :map {:id 3, :name "Unknown"}}
答案 1 :(得分:1)
对于这么简单的事情,多方法可能有点过分。我只使用cond
:
(ns tst.demo.core
(:require
[cheshire.core :as cheshire]
[clojure.java.io :as io] ))
(let [json-str (slurp (io/resource "data.json"))
edn-data (cheshire/parse-string json-str true) ; need `true` to emit keywords
]
(doseq [[type id-name-map] edn-data]
(cond
(= type :foo) (println :foo-proc id-name-map)
(= type :bar) (println :bar-proc id-name-map)
:else (println :other-proc id-name-map) )))
结果:
:foo-proc {:id 2, :name foo2}
:bar-proc {:id 2, :name bar2}
需要project.clj
中的以下内容:
:dependencies [
[cheshire "5.8.0"]
....
以及您的数据位于resources/data.json
的位置:
~/expr/demo > cat resources/data.json
{
"foo": {
"id": 1,
"name": "foo1"
},
"bar": {
"id": 1,
"name": "bar1"
}, ....