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

55ooxyrt  于 5个月前  发布在  Scala
关注(0)|答案(2)|浏览(55)

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

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

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

kninwzqo

kninwzqo1#

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

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

字符串

deyfvvtc

deyfvvtc2#

如果只需要转换值,而不需要转换键,可以使用用途:

def transform(fn: String => String)(json: Json): Json =
  json
    .mapString(fn)
    .mapArray(_.map(transform(fn)))
    .mapObject(_.mapValues(transform(fn)))

字符串
但是,要注意该函数是递归的。

相关问题