Sudev Ambadi Sudev Ambadi - 3 months ago 21
Scala Question

Python like json parsing in Scala ?

Coming from python background I find it hard to parse JSON properly in Scala(Especially when JSON don't follow a specific schema).

Python parses JSON with ease and you can iterate through elements using

dict.keys()
,
dict.values()
etc.

Is there any good JSON library in Scala, which can parse JSON without having to define a
case class
. This seems extremely painful if we have nested JSON.

I tried Gson and Json4s both of them requires many case class to reflect JSON to a scala object...Can we parse and extract values without doing all of this ?

Answer

Argonaut is great library. It has excellent facilities for defining codecs, traversing JSON and parsing JSON.

This example (from the documentation) shows parsing without defining a case class:

package argonaut.doc

import scalaz._, Scalaz._
import argonaut._, Argonaut._

object ParseExample extends App {

  val json = """
    { "name" : "Toddler", "age" : 2, "greeting": "gurgle!" }
  """

  // Parse getting either error message or json
  val result: String \/ Json =
    Parse.parse(json)

  // Parse ignoring error messages
  val option: Option[Json] =
    Parse.parseOption(json)

  // Parse handling success and failure with functions
  val greeting1: String =
    Parse.parseWith(json, _.field("greeting").flatMap(_.string).getOrElse("Hello!"), msg => msg)

  // Parse handling success and providing a default for failure
  val greeting2: String =
    Parse.parseOr(json, _.field("greeting").flatMap(_.string)getOrElse("Hello!"), "Oi!")

}
Comments