I have a map like this:
Map("first_key"->"first_value",
"second_key"->Map("second_first_key"->"second_first_value"))
How can I recursively convert all keys to like this in scala:
Map("firstKey"->"first_value",
"secondKey"->Map("secondFirstKey"->"second_first_value"))
This should do what you want:
def convert(m: Map[String, Any]): Map[String, Any] = {
m.map {
case (k, v) =>
val k2 = toCamel(k)
val v2: Any = v match {
case s: String => s
case x: Map[String, Any] => convert(x)
}
k2 -> v2
}
}
def toCamel(s: String): String = {
val split = s.split("_")
val tail = split.tail.map { x => x.head.toUpper + x.tail }
split.head + tail.mkString
}
val m = Map("first_key"->"first_value",
"second_key"->Map("second_first_key"->"second_first_value"))
convert(m)
// Map(firstKey -> first_value, secondKey -> Map(secondFirstKey -> second_first_value))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With