Skip to content

Instantly share code, notes, and snippets.

@asheshambasta
Created February 13, 2017 09:16
Show Gist options
  • Save asheshambasta/95f2a093a4d3e374cbe7891decdac059 to your computer and use it in GitHub Desktop.
Save asheshambasta/95f2a093a4d3e374cbe7891decdac059 to your computer and use it in GitHub Desktop.
Very simple + untidy json flattener.
import play.api.libs.json.{JsObject, JsValue, Json}
implicit class JsonFlatten(v: JsValue) {
def toMap(pref: String = ""): Map[String, String] = if (v.isIterable) v.validate[Seq[JsObject]] map { jsons =>
jsons.foldLeft(Map.empty[String, String]) {
case (acc, json) => acc ++ json.toMap(pref)
}
} getOrElse Map.empty[String, String] else v.validate[Map[String, JsValue]] map { mp =>
mp.foldLeft(Map.empty[String, String]) {
case (acc, (k, value)) if value.isFlat => acc + (s"$pref.$k" -> value.toString)
case (acc, (k, value)) => acc ++ value.toMap(s"$pref.$k")
}
} getOrElse Map.empty[String, String]
def isFlat = !(v.isNestable || v.isIterable)
def isNestable = v.validate[JsObject].isSuccess
def isIterable = v.validate[Seq[JsValue]].isSuccess
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment