10
votes

I am pretty new to Clojure. I have a map of results from a database and it contains key values such as:

{:Unique Product ID "09876" :ProductName "XYZ"}

I want to retrieve the values from the map but I am having problems getting the Unique Product ID.

ProductID (str ( map-name ":Unique Product ID"))

Product Name works fine using:

ProductName (str ( map-name :ProductName"))

I'm not sure how to handle the space in the Product ID field key. How should I retrieve the value for that key from the map?

Thanks

3

3 Answers

15
votes

Try (keyword "Unique Product ID")

9
votes

Space is not a valid character in a keyword, you are trying to do something that will almost certainly cause pain in the future.

Note that the keyword function does not validate it's input, so @jeff-johnston is incorrect I'm afraid.

Lengthy discussion here:

https://groups.google.com/d/topic/clojure/WvXYkvLoQhI/discussion

clojuredocs was updated with new docstrings following that discussion see here:

http://clojuredocs.org/clojure_core/clojure.core/keyword

1
votes

You can use (keyword) as Jeff indicates, but I think you would be better off in general if you transformed the map you get back from the database query into one whose keys have no spaces. I find this function useful for the purpose:

(defn despace [m] 
  (zipmap (map #(keyword (clojure.string/replace (name %) " " "_")) (keys m))
          (vals m)))

Then use underscores in place of the spaces:

(:Unique_Product_ID (despace {(keyword "Unique Product ID") "09876" :ProductName "XYZ"}))
#=> "09876"