Skip to content

Instantly share code, notes, and snippets.

@temon
Created July 17, 2019 07:35
Show Gist options
  • Save temon/57199a71baa7403e95ff09e97edc70e3 to your computer and use it in GitHub Desktop.
Save temon/57199a71baa7403e95ff09e97edc70e3 to your computer and use it in GitHub Desktop.
implicit class JsonImprovement(json: JsValue) {
def withoutNull = {
def internal(newJson: JsValue): JsValue = {
newJson match {
case JsObject(fields) =>
if (fields.isEmpty) JsNull
else {
fields.foldLeft(new JsObject(Map()))((agg, field) =>
field match {
case (name, JsArray(arrayValues)) => {
val seqJsonVal = arrayValues.map{ arrayValue =>
internal(arrayValue)
}
agg + (name, JsArray(seqJsonVal))
}
case (_, JsNull) => agg
case other@(name, value: JsArray) => {
value.value.map { insideVal =>
val nested = internal(insideVal)
agg + (name, nested)
}.foldLeft(Json.obj())((obj, a) => obj.deepMerge(a.as[JsObject]))
}
case (name, value: JsObject) => {
val nested = internal(value)
agg + (name, nested)
}
case other@(name, value) => agg + other
})
}
case JsArray(arrayValues) => {
arrayValues.map{ arrayValue =>
val nested = internal(arrayValue)
nested
}.foldLeft(Json.arr()) ((obj, a) => obj.append(a))
}
case other => other
}
}
internal(json)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment