Is there a simpler approach to providing a default value for an invalid or blank string field when parsing JSON with argonaut?

I am using Argonaut to parse JSON strings. There is a requirement: if any field is not provided or is empty or empty, replace it with the string "not attached".

I have a solution, but it seems very complicated:

case class User(name: String, home: String)

implicit def UserDecodeJson: DecodeJson[User] = DecodeJson(j => for {
  name <- (j --\ "name").as[BlankAsNonSupplied]
  home <- (j --\ "home").as[BlankAsNonSupplied]
} yield User(name.value, home.value))

case class BlankAsNonSupplied(value: String)

implicit def BlankAsNonSuppliedDecodeJson: DecodeJson[BlankAsNonSupplied] = DecodeJson.withReattempt(a => {
  val v =
    .map(BlankAsNonSupplied.apply).getOrElse(BlankAsNonSupplied("not supplied"))


You can see that it is BlankAsNonSuppliedDecodeJson

very complex and difficult to understand. Is there a way to make this (or the whole example) easier?


source to share

All Articles