How do I turn this JSON array into an actual array with argonaut?

85 Views Asked by At

I have this JSON in a separate file:

{
  "TestModel" : [
    {"query" : "select * from ci_lmaggregation.elementstest where hash_aggregation_key = 0 ALLOW FILTERING "},
    {"query" : "select * from ci_lmaggregation.elementstest where hash_aggregation_key = 1 ALLOW FILTERING "},
    {"query" : "select * from ci_lmaggregation.elementstest where hash_aggregation_key = 2 ALLOW FILTERING "}
  ]
}
}

I'm trying to follow their quickstart, but it's not even finding the "decodeOption", or "Parse.parse" or anything else. I'm extremely confused?

  val input_file = "[path]/FeatureMapping.json"
  val json_content = scala.io.Source.fromFile(input_file).mkString
  //it can't find decodeOption
  val json_data = json_content.decodeOption[List[Person]].getOrElse(Nil)
  //or Parse.parse (which should work given this http://argonaut.io/doc/parsing/)
  val jdata = Parse.parse(json_content)

So I'm not entirely sure how to accomplish what I want to do. I've tried following this: Parse JSON array using Scala Argonaut

And the getting started guide on their website, but neither seem to have an example for how to handle the case of an array as here. Also, the code examples in the SO post, codec3 shows up as not existing so I'm confused there too.

I just want an array of queries as strings out of the file, why isn't there a simple way to do this like in python?

1

There are 1 best solutions below

2
On BEST ANSWER

Use the Dijon library. It is a safe and efficient way to work with schema-less JSON using Scala these days.

Add dependency:

libraryDependency += "me.vican.jorge" %% "dijon" % "0.5.0"

Import Scala's dynamic type feature and the library package:

import scala.language.dynamics._
import dijon._

Then parse and select required values from your JSON:

val json = parse(
"""{
   |  "TestModel" : [
   |    {"query" : "select * from ci_lmaggregation.elementstest where hash_aggregation_key = 0 ALLOW FILTERING "},
   |    {"query" : "select * from ci_lmaggregation.elementstest where hash_aggregation_key = 1 ALLOW FILTERING "},
   |    {"query" : "select * from ci_lmaggregation.elementstest where hash_aggregation_key = 2 ALLOW FILTERING "}
   |  ]
   |}""".stripMargin
)
assert(json.TestModel.toSeq.map(_.query) == Seq(
  "select * from ci_lmaggregation.elementstest where hash_aggregation_key = 0 ALLOW FILTERING ",
  "select * from ci_lmaggregation.elementstest where hash_aggregation_key = 1 ALLOW FILTERING ",
  "select * from ci_lmaggregation.elementstest where hash_aggregation_key = 2 ALLOW FILTERING "
))