0

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"}]
3
  • I don't understand the question, emp looks like it's already in the format you're asking for. Commented Apr 21, 2022 at 20:25
  • Hi Musa, I think you mistakenly have put the Map you want to obtain instead of the string you want to parse. Or did I misunderstand your question? Commented Apr 21, 2022 at 20:27
  • Im new to scala. String looks like below. Here Map is just word. "Map(employees -> [{"id":"100","name":"Alex","state":"MA"},{"id":"101","name":"Agni","state":"CA"},{"id":"102","name":"Sharo","state":"TX"}])" Commented Apr 21, 2022 at 20:32

1 Answer 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")
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks @Decly ... How can I convert into Map(String,String) in single line ?
You can do something like Map(emp.substring(emp.indexOf("(") + 1, emp.indexOf(" -> ")) -> emp.substring(emp.indexOf(" -> ") + 4, emp.indexOf(")")))

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.