'How can I split string like key and value using scala in efficient way:

How can I split string like key and value using scala in efficient way:

I would like to split below emp string into key value pair.

var emp = "Map(employees -> [{"id":"100","name":"Alex","state":"MA"},{"id":"101","name":"Agni","state":"CA"},{"id":"102","name":"Sharo","state":"TX"}])"

Need to parse like below :

key: employees 
value : [{"id":"100","name":"Alex","state":"MA"},{"id":"101","name":"Agni","state":"CA"},{"id":"102","name":"Sharo","state":"TX"}]


Solution 1:[1]

This code parse the string into 2 others (key and value):

object Parser extends App {
  
    val emp = "Map(employees -> {\"id\":\"100\",\"name\":\"Alex\",\"state\":\"MA\"},{\"id\":\"101\",\"name\":\"Agni\",\"state\":\"CA\"},{\"id\":\"102\",\"name\":\"Sharo\",\"state\":\"TX\"}])"
    
    val key = emp.substring(emp.indexOf("(") + 1, emp.indexOf(" -> "))
    val value = emp.substring(emp.indexOf(" -> ") + 4, emp.indexOf(")"))

    println(s"key: $key");
    println(s"value: $value")
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1