3

I have a string that is a Json array of two objects.

> val ss = """[ {"key1" :"value1"}, {"key2":"value2"}]"""

I want to use the Play Json libraries to deserialize it and create a map from the key values to the objects.

def deserializeJsonArray(ss:String):Map[String, JsValue] = ???
// Returns Map("value1" -> {"key1" :"value1"}, "value2" -> {"key2" :"value2"})

How do I write the deserializeJsonArray function? This seems like it should be easy, but I can't figure it out from either the Play documentation or the REPL.

W.P. McNeill
  • 16,336
  • 12
  • 75
  • 111

1 Answers1

2

I'm a bit rusty, so please forgive the mess. Perhaps another overflower can come in here and clean it up for me.

This solution assumes that the JSON is an array of objects, and each of the objects contains exactly one key-value pair. I would highly recommend spicing it up with some error handling and/or pattern matching to validate the parsed JSON string.

def deserializeJsonArray(ss: String): Map[String, JsValue] = {

  val jsObjectSeq: Seq[JsObject] = Json.parse(ss).as[Seq[JsObject]]

  val jsValueSeq: Seq[JsValue] = Json.parse(ss).as[Seq[JsValue]]

  val keys: Seq[String] = jsObjectSeq.map(json => json.keys.head)

  (keys zip jsValueSeq).toMap
}
David Kaczynski
  • 1,246
  • 2
  • 20
  • 36