Home > Software engineering >  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:

Time:04-22

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"}]

CodePudding user response:

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")
}
  • Related