1
votes

I am new to scala and I am trying to parse a JSON shown below

val result = JSON.parseFull("""
  {"name": "Naoki",  "lang": ["Java", "Scala"] , "positionandvalue": ["5:21", "6:24", "7:6"]}
""")
result: Option[Any] = Some(Map(name -> Naoki, lang -> List(Java, Scala), positionandvalue -> List(5:21, 6:24, 7:6)))

And get the parsed values in a Map

val myMap = result match {
  case Some(e) => e
  case None => None
}
myMap: Any = Map(name -> Naoki, lang -> List(Java, Scala), positionandvalue -> List(5:21, 6:24, 7:6))

What I need is 1. To get the key as a new variable (to be used as metadata to validate the file) with its corresponding value assigned to it. Something like,

val name = "Naoki"
  1. positionandvalue -> List(5:21, 6:24, 7:6). This variable indicates the List of(Position of string delimited a in file:length of string in position). How can I use this variable to satisfy the requirement.
1
sorry. not able to understand what is required here exactly. can you please reword the requirement? - rogue-one

1 Answers

0
votes

you cannot dynamically create the variables name and positionandvalue from the Map key. However they can be statically created using the below approach.

val result: Option[Any] = Some(Map("name" -> "Naoki", "lang" -> List("Java", "Scala"), "positionandvalue" -> List("5:21", "6:24", "7:6")))

val myMap: Map[String, Any] = result match {
  case Some(e: Map[String, Any] @unchecked) => e
  case _ => Map()
}

val name = myMap.get("name") match { 
  case Some(x: String) => x 
  case _ => throw new RuntimeException("failure retrieving name key")
}

val positionandvalue = myMap.get("positionandvalue") match { 
  case Some(x: List[String] @unchecked) => x.map(y => (y.split(":") match {case Array(x1,x2) => x1 -> x2})).toMap
  case _ => throw new RuntimeException("failure retrieving positionandvalue key")
}

positionandvalue: scala.collection.immutable.Map[String,String] = Map(5 -> 21, 6 -> 24, 7 -> 6)