Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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