Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a String to a Map

Tags:

scala

Given a String : {'Name':'Bond','Job':'Agent','LastEntry':'15/10/2015 13:00'}

I want to parse it into a Map[String,String], I already tried this answer but it doesn't work when the character : is inside the parsed value. Same thing with the ' character, it seems to break every JSON Mappers...

Thanks for any help.

like image 832
Will Avatar asked Mar 21 '26 05:03

Will


2 Answers

Let

val s0 = "{'Name':'Bond','Job':'Agent','LastEntry':'15/10/2015 13:00'}"
val s = s0.stripPrefix("{").stripSuffix("}")

Then

(for (e <- s.split(",") ; xs = e.split(":",2)) yield xs(0) -> xs(1)).toMap

Here we split each key-value by the first occurrence of ":". Further this is a strong assumption, in that the key does not contain any ":".

like image 165
elm Avatar answered Mar 24 '26 01:03

elm


You can use the familiar jackson-module-scala that can do this in much better scale.

For example:

val src = "{'Name':'Bond','Job':'Agent','LastEntry':'15/10/2015 13:00'}"
val mapper = new ObjectMapper() with ScalaObjectMapper
mapper.registerModule(DefaultScalaModule)
val myMap = mapper.readValue[Map[String,String]](src)
like image 32
Avihoo Mamka Avatar answered Mar 24 '26 03:03

Avihoo Mamka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!