1

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

2
  • shouldn't that be (keyword "bar") instead? Commented Oct 12, 2015 at 15:41
  • well yes, (keyword "bar") works ... but I have ":bar" in the string not "bar" Commented Oct 12, 2015 at 15:42

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

thanks for that ... it feels a bit hacky to wrangle the string first, but looks like that's the only way.
It is a bit hacky, because you have the string ":asd" to begin with. Where did that string come from? More likely, you can address this problem closer to its source, by generating a more reasonable string input in the first place.
yeah I ended up doing just that ... I used (name ":asd") before it got stored ... so I could just used (keyword "asd") on the string. Thanks for the advice.
0

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"

Comments

0

This works:

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

Or of course:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.