0

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.

Tim
  • 26,753
  • 2
  • 16
  • 29
  • Try using `match` on the object to get the `List` and then `collect` on that `List` to get the key/value pairs, and then `collect` on the value to get the strings and finally `toMap` at the end. See how far you get and post the code if you can't get it working. – Tim Apr 05 '22 at 10:37
  • BEWARE: [json4s is vulnerable under DoS/DoW attacks!](https://github.com/json4s/json4s/issues?utf8=%E2%9C%93&q=is%3Aissue+is%3Aopen+denial) – Andriy Plokhotnyuk Jul 04 '22 at 08:32

1 Answers1

0

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).

kag0
  • 5,624
  • 7
  • 34
  • 67