Given a CSV file, how do I take the values in each row and convert it into a map?

1,082 views
Skip to first unread message

Shelley Tong

unread,
Jun 12, 2014, 5:17:58 PM6/12/14
to clo...@googlegroups.com
kinda like a key value pair for each row

Marc Limotte

unread,
Jun 12, 2014, 5:39:14 PM6/12/14
to clo...@googlegroups.com
See https://github.com/clojure-cookbook/clojure-cookbook/blob/master/04_local-io/4-20_read-write-csv.asciidoc

Which will give you a seq of the values for each row.  To get Maps, try this:

(def headers ["colA" "colB" ...])
(map (partial zipmap headers) result-of-read-csv)

If your headers are the first line in your CSV, then use (first result-of-read-csv) to get the headers and (rest ...) for the data.




On Thu, Jun 12, 2014 at 5:17 PM, Shelley Tong <shelley...@gmail.com> wrote:
kinda like a key value pair for each row

--
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clo...@googlegroups.com
Note that posts from new members are moderated - please be patient with your first post.
To unsubscribe from this group, send email to
clojure+u...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en
---
You received this message because you are subscribed to the Google Groups "Clojure" group.
To unsubscribe from this group and stop receiving emails from it, send an email to clojure+u...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Devin Walters

unread,
Jun 12, 2014, 6:13:14 PM6/12/14
to clo...@googlegroups.com
I tend to do this:

(require '[clojure.data.csv :as csv])
(require '[clojure.java.io :as io])
(require '[clojure.walk :as walk])

(let [[header rows] (-> "my.csv"
                        io/file
                        io/reader
                        csv/read-csv)]
  (map #(-> (zipmap header %)
            (walk/keywordize-keys))
       rows))

=> ({:a "foo" :b "bar"} {:a "baz" :b "buzz"} ...)

Cheers,
-- 
Devin Walters

Reply all
Reply to author
Forward
0 new messages