Reputation: 9451
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.
Upvotes: 4
Views: 20751
Reputation: 19328
os-lib and upickle are better options for reading and parsing JSON data.
val jsonString = os.read(os.pwd/"src"/"test"/"resources"/"scala_input.json")
val data = ujson.read(jsonString)
data("edges_file").str // "/path/edges.json.gz"
data("seed_file").str // "/path/seed.json.gz"
This code is way cleaner than what JSON.parseFull
allows for. See here for more details on how to use these libs.
Upvotes: 6
Reputation: 37852
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...
Upvotes: 6