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

4

使用CIRCE库和Cats,能够转换任意Json对象中的所有字符串值,如下所示,这将非常有用:

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

是否有可能将所有字符串值 (topLevelVal,nestedVal,insideArrayVal1,insideArrayVal2) 转换为大写字母(或者进行任何其他字符串变换)?


1
哦,是的,这将非常有帮助! - Anton v B
1个回答

3
您可以自己编写递归函数。大致应该是这样的:
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))

1
非常好。它大大缩短了我的解决方案,现在它只是: def transformStringValues(f: String => String, json: Json): Json = json.mapString(f).mapArray(a => a.map(transformStringValues(f, _))).mapObject(obj => JsonObject(obj.toMap.mapValues(transformStringValues(f, _)).toSeq :_*)) (在评论中无法很好地格式化,但也可以作为单行代码运行) - Tobias Roland

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接