0

I have a string:

{:id 1, :name "Ab Bc Cd", :sex "M", :birth "01.01.1999", :address "Street 1", :oms "0001"}

And i need to convert it to HashMap but

(hash-map my-str)

returns {} So i splited it:

(s/split my-str ",")

And it returns

[:id 1  :name "Ab Bc Cd"  :sex "M"  :birth "01.01.1999"  :address "Street 1"  :oms "0001"]

Then

for [x my-arr]
(hash-map x)

returns

({} {} {} {} {} {})

How can i do this?

3 Answers 3

7

If you got this string intentionally, then use

clojure.edn/read-string

E.g.

user=> (require 'clojure.edn)
nil
user=> (clojure.edn/read-string (slurp "x.edn"))
{:id 1, :name "Ab Bc Cd", :sex "M", :birth "01.01.1999", :address "Street 1", :oms "0001"}
Sign up to request clarification or add additional context in comments.

1 Comment

note the clojure.edn in that recommendation, that's the safe and proper way for trusted input. clojure.core/read-string will in some cases run arbitrary cuddle passed in the input. I have found this in public sites out there on the internet (with permission) so remember to put that clojure.edn
2

your example is almost there!

you can finish it with a call to

(into {} your-result-so-far)

into comes up a lot of you get into the habit of looking for it.

2 Comments

I'm not sure this will work, since (str/split s #",") should yield a result like ["{:id 1" ...]
@AlanThompson "result-so-far" would be the result of OPs for (which lacks some parens)
0

The shortest way would be clojure.core's read-string - it reads from the string and executes the command for building an object:

(def s "{:id 1, :name \"Ab Bc Cd\", :sex \"M\", :birth \"01.01.1999\", :address \"Street 1\", :oms \"0001\"}")
(read-string s)
;; => {:id 1, :name "Ab Bc Cd", :sex "M", :birth "01.01.1999", :address "Street 1", :oms "0001"}

The documentation says:

Reads one object from the string s. Optionally include reader options, as specified in read. Note that read-string can execute code (controlled by read-eval), and as such should be used only with trusted sources. For data structure interop use clojure.edn/read-string

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.