Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove keys with null values from Argonaut Json objects

Tags:

scala

argonaut

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...

like image 964
sungiant Avatar asked Oct 28 '25 05:10

sungiant


1 Answers

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!

like image 199
Iain J. Reid Avatar answered Oct 29 '25 19:10

Iain J. Reid



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!