Search code examples
scalaargonaut

Converting JSON field names in argonaut


I'm writing a library to convert JSON responses from an API for backwards compatibility reasons. And what I need to do is take in arbitrary JSON, and change certain field names. I'm using scala and argonaut, but I don't see any way in the docs or examples of changing the FIELD names, only the values.


Solution

  • I ended up folding over the object I need to convert and adding to a map, and then creating a new json object.

    val conversionMap = Map("a" -> "b")
    
    Json(
      j.objectOrEmpty.toMap.foldLeft(Map.empty[JsonField, Json]) {
        case (acc, (key, value)) =>
          acc.updated(conversionMap.getOrElse(key, key), j.fieldOrNull(key))
      }.toSeq: _*
    )