Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure map key with spaces in the key name

Tags:

map

clojure

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

like image 220
user1494355 Avatar asked Jul 01 '12 14:07

user1494355


3 Answers

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

like image 122
sw1nn Avatar answered Oct 17 '22 20:10

sw1nn


Try (keyword "Unique Product ID")

like image 15
Jeff Johnston Avatar answered Oct 17 '22 20:10

Jeff Johnston


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"
like image 2
Mark Reed Avatar answered Oct 17 '22 20:10

Mark Reed