[英]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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.