Converting String to Hashmap

938 views
Skip to first unread message

Antix

unread,
Jun 18, 2012, 11:18:43 AM6/18/12
to Clojure
Hi Guys,
I'm very new to clojure and searching for a way to convert a given
String to a Hashmap as far as this is possible.
I thought already about the use of a macro, but all the different
quotes are a little bit confusing for me.

Is it possible to create a Hashmap or some similar structure by using
a given String.

My Input-String is something like: :Name "John", :age 20, :gender
"n"
Is it possible to convert this to a hashmap similar to this:
(def hashm {:Name "John", :age 20, :gender "n" }) ?

Jay Fields

unread,
Jun 18, 2012, 12:44:42 PM6/18/12
to clo...@googlegroups.com
first of all, what gender is "n"? =)


--
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

Tassilo Horn

unread,
Jun 18, 2012, 2:25:02 PM6/18/12
to clo...@googlegroups.com
Jay Fields <j...@jayfields.com> writes:

> first of all, what gender is "n"? =)

*N*erd! What else could it be?!

Bye,
Tassilo

Antix

unread,
Jun 18, 2012, 3:46:13 PM6/18/12
to Clojure
Thank you. That solution worked for me. @Tassilo: haha, yeah a nerd
should definedly deserves an own gender ;D

On 18 Jun., 18:44, Jay Fields <j...@jayfields.com> wrote:
> first of all, what gender is "n"? =)
>
> http://blog.jayfields.com/2011/03/clojure-eval-ing-string-in-clojure....

David Powell

unread,
Jun 19, 2012, 6:53:30 AM6/19/12
to clo...@googlegroups.com
Use the built in read-string function.:
(read-string (str "{" s "}")))

Don't use eval or load-string.  read-string is safer, faster, and won't hit JVM size limits.

Also, if the input isn't trusted, you should bind *read-eval* to false, to avoid being subject to running hostile user-supplied code:

(defn parse-map
  [s]
  (binding [*read-eval* false]
    (read-string (str "{" s "}"))))

-- 
Dave

Reply all
Reply to author
Forward
0 new messages