[英]Get key of PersistentArrayMap in clojure
我的問題可能有點容易回答,但是我才剛剛開始學習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元素類型...有人可以幫我嗎?
通過將其視為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"}}
對於這種簡單的事情,多方法可能會顯得過大。 我只是用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"
}, ....
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.