stukennedy
stukennedy

Reputation: 1108

Clojure: how to get from a map using a string key

If I have a map like this:

(def foo {:bar "foobar"})

And I've been passed the key :bar as a string (i.e. ":bar") I want to be able to access the value from the map doing something like

(get foo (symbol ":bar"))

which I thought would work, because (symbol ":bar") is :bar ... but it just returns nil

Upvotes: 1

Views: 1590

Answers (3)

shmish111
shmish111

Reputation: 3787

This works:

((read-string ":bar") {:bar "foobar"})
=> "foobar"

Or of course:

(get {:bar "foobar"} (read-string ":bar"))

Upvotes: 0

north_celt
north_celt

Reputation: 25

If your string really is ":bar", just do a replace to remove the colon and then use keyword to convert it to a keyword.

(def foo {:bar "foobar"})

(foo (keyword (clojure.string/replace ":bar" #"\:" ""))) => "foobar"

Upvotes: 0

JustAnotherCurious
JustAnotherCurious

Reputation: 2240

If you need to make from string ":asd" a keyword :asd you do something like this:

> (= (read-string ":asd") (keyword (subs ":asd" 1)) :asd)
true

Your code with (symbol ":asd") just print itself like :asd but is actually a symbol, not keyword.

Upvotes: 3

Related Questions