Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala read and parse JSON

Tags:

java

json

scala

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.

like image 201
LearningSlowly Avatar asked Oct 15 '25 19:10

LearningSlowly


2 Answers

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...
like image 109
Tzach Zohar Avatar answered Oct 18 '25 07:10

Tzach Zohar


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.

like image 27
Powers Avatar answered Oct 18 '25 07:10

Powers