Daniel Doubrovkine bio photo

Daniel Doubrovkine

aka dB., @ShopifyEng, @OpenSearchProj, ex-@awscloud, former CTO @artsy, +@vestris, NYC

Email Twitter LinkedIn Github Strava
Creative Commons License

While XML is a first-class citizen in Scala, there’s no “default” way to parse JSON. So searching StackOverflow and Google yields all kinds of responses that seem unnecessarily complicated.

Jackson

This SO answer describes the easiest solution, which gives you a Map[String, Object], use jackson-module-scala.

import scala.io._ import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.module.scala.DefaultScalaModule import com.fasterxml.jackson.module.scala.experimental.ScalaObjectMapper  object Main {   def main(args: Array[String]): Unit = {     val filename = args.head     // read     println(s"Reading ${args.head} ...")     val json = Source.fromFile(filename)     // parse     val mapper = new ObjectMapper() with ScalaObjectMapper     mapper.registerModule(DefaultScalaModule)     val parsedJson = mapper.readValue[Map[String, Object]](json.reader())     println(parsedJson)   } } 

Here’s the output from a sample JSON.

Reading example.json ... Map(glossary -> Map(title -> example glossary, GlossDiv -> ..., GlossTerm -> Standard Generalized Markup Language))))) 

Liftweb JSON

The lift-json JSON parser in Liftweb does a good job, too, but returns JObject-like types instead of raw String or Map[String, Object].

import scala.io._ import net.liftweb.json._  object Main {   def main(args: Array[String]): Unit = {     val filename = args.head     // read     println(s"Reading ${args.head} ...")     val json = Source.fromFile(filename)     // parse     let parsedJson = net.liftweb.json.parse(json.mkString)     println(parsedJson)   } } 

Here’s the output from a sample JSON.

JObject(List(JField(glossary, ...))) 

Source

The code above is here, maybe someone can contribute an example for writing JSON?