LearningSlowly LearningSlowly - 1 month ago 12
Scala Question

Scala read and parse JSON

I am new to Scala. I have a JSON file, entitled

scala_input.json
containing two items:

{
"edges_file": "/path/edges.json.gz",
"seed_file": "/path/seed.json.gz"
}


I wish to open the file, parse and attribute two
val
from this file. I have tried:

val input_file = "/path/scala_input.json"
val json_data = JSON.parseFull(input_file)
val edges_file = json_data.get.asInstanceOf[Map[String, Any]]("edges_file").asInstanceOf[String]
val seeds_file = json_data.get.asInstanceOf[Map[String, Any]]("seed_file").asInstanceOf[String]]


However, this returns
java.util.NoSuchElementException: None.get
. What is it I have not defined?
json_data
and
input_file
are correct and I am sure that
edges_file
and
seed_file
exist.

Answer

JSON.parseFull expects a JSON String, not a path to a file containing such a String. So - you should first load the file and then parse it:

val input_file = "./scala_input.json"
val json_content = scala.io.Source.fromFile(input_file).mkString
val json_data = JSON.parseFull(json_content)
// go on from there...
Comments