Created
February 13, 2017 09:16
-
-
Save asheshambasta/95f2a093a4d3e374cbe7891decdac059 to your computer and use it in GitHub Desktop.
Very simple + untidy json flattener.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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