Parsing JObject In Scala

715 Views Asked by At

I am using json4s for parsing a json object which gives me result like this:

JObject(List((x,JArray(List(JString(x_value)))), 
(y,JArray(List(JString(y_value)))), 
(z,JArray(List(JString(z_value))))))

Now I want to convert it like this:

Map("x" -> Array("x_value"), 
"y" -> Array("y_value"),
"z" -> Array("z_value"))

I am not sure how to do this. I am new to this. I tried using case class but I got confused because case class will give me separate x, y, z values but these attributes are dynamic and can have more.

1

There are 1 best solutions below

0
kag0 On

The Json4s way to do this would be simply

val json = JObject(List((x,JArray(List(JString(x_value)))), (y,JArray(List(JString(y_value)))), (z,JArray(List(JString(z_value))))))

json.extract[Map[String, Array[String]]]

But I would recommend that you use Seq or List instead of Array (we don't generally like mutable arrays much in Scala).

Also in typical stack overflow fashion, I'd recommend that you not use Json4s. It has failed it's goal of "One AST to rule them all" and today there are better, safer libraries to use. Look at Play JSON (good support for validating input fields), Circe (functional programming support with cats), ninny JSON (self plug, just compare the docs to json4s and see if it's clearer), or uJson (mutable json objects and api familiar to those coming from scripting languages).