4

How can an extension method be written to remove all keys with a null value from an Argonaut Json object:

I tried this:

package object Extensions {
  implicit class JsonExtensions(val json: Json) extends AnyVal {
    def removeNulls: Json = {
      json.withObject(j => JsonObject.from (j.toMap.filter(!_._2.isNull).toList))
    }
  }
}

but it only seems to be removing keys with null values at the top level of the Json object...

sungiant
  • 3,152
  • 5
  • 32
  • 49
  • My understanding of that library is that you have to explicitly define how many levels of nesting you want the lenses to drill into. –  Aug 02 '16 at 19:27
  • You need to recurse into the nodes to do that. – pedrofurla Aug 02 '16 at 21:12

1 Answers1

6

Argonaut supports this internally, you can use PrettyParams to do what you're after:

def removeNulls: Json = {
  json.pretty(PrettyParams.nospace.copy(dropNullKeys = true)).toJson
}

Hope this covers your question!

Iain J. Reid
  • 978
  • 1
  • 11
  • 23