用 Circe 递归替换所有 JSON 字符串值

Replacing all JSON String values recursively with Circe

使用 CIRCE 库和 Cats,能够转换任意 Json 对象的所有 string 值将非常有用,例如

{
  "topLevelStr" : "topLevelVal", 
  "topLevelInt" : 123, 
  "nested" : { "nestedStr" : "nestedVal" },
  "array" : [
    { "insideArrayStr" : "insideArrayVal1", "insideArrayInt" : 123},
    { "insideArrayStr" : "insideArrayVal2", "insideArrayInt" : 123}
   ]
}

是否可以将所有字符串值(topLevelVal, nestedVal, insideArrayVal1, insideArrayVal2) 转换为大写(或任何任意字符串转换)?

你可以自己写递归函数。应该是这样的:

import io.circe.{Json, JsonObject}
import io.circe.parser._


def transform(js: Json, f: String => String): Json = js
  .mapString(f)
  .mapArray(_.map(transform(_, f)))
  .mapObject(obj => {
    val updatedObj = obj.toMap.map {
      case (k, v) => f(k) -> transform(v, f)
    }
    JsonObject.apply(updatedObj.toSeq: _*)
  })

val jsonString =
  """
    |{
    |"topLevelStr" : "topLevelVal",
    |"topLevelInt" : 123, 
    | "nested" : { "nestedStr" : "nestedVal" },
    | "array" : [
    |   {
    |      "insideArrayStr" : "insideArrayVal1",
    |      "insideArrayInt" : 123
    |   }
    |  ]
    |}
  """.stripMargin

val json: Json = parse(jsonString).right.get
println(transform(json, s => s.toUpperCase))