简体   繁体   中英

Get key of PersistentArrayMap in clojure

My question could be a little bit easy to answer but I've just started to learn clojure and I have no idea of how to do this.

I have a JSON file that I have read and parsed. Now I have to get each element of this JSON and treat then according with the type. For example, I have the JSON:

{
  "foo": {
    "id": 1,
    "name": "foo1"
  },
  "bar": {
    "id": 1,
    "name": "bar1"
  },
  "foo": {
    "id": 2,
    "name": "foo2"
  },
  "bar": {
    "id": 2,
    "name": "bar2"
  }
}

So, I want to make a function that iterate on every element of my JSON and then call another function with multiples declarations for each element type of my JSON.

The problem is that I don't know how I can get the JSON element type... Can someone help me?

You can get all key-value pairs of a map by treating it as a Clojure sequence. Then it behaves as a sequence of two-element vectors, a sequence of MapEntry elements to be more precise. When you call first on a MapEntry you will get the key.

So (first (seq {:a 1})) returns [:a 1] and (first [:a 1]) returns :a , the key. The call to seq in this example is not needed, but is only there to make the example more explicit.

You could then write a case expression to do things according to the key. To make it more extensible you could use multimethods.

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

Multimethods might be overkill for something this simple. I'd just use 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) )))

with results:

:foo-proc {:id 2, :name foo2}
:bar-proc {:id 2, :name bar2}

which requires the following in project.clj :

  :dependencies [
    [cheshire "5.8.0"]
      ....

and where your data is in resources/data.json :

~/expr/demo > cat resources/data.json 
{
  "foo": {
    "id": 1,
    "name": "foo1"
  },
  "bar": {
    "id": 1,
    "name": "bar1"
  },  ....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM