使用CIRCE库和Cats,能够转换任意Json对象(例如
)的所有string
值将非常有用。
{
"topLevelStr" : "topLevelVal",
"topLevelInt" : 123,
"nested" : { "nestedStr" : "nestedVal" },
"array" : [
{ "insideArrayStr" : "insideArrayVal1", "insideArrayInt" : 123},
{ "insideArrayStr" : "insideArrayVal2", "insideArrayInt" : 123}
]
}
是否可以将所有字符串值(topLevelVal, nestedVal, insideArrayVal1, insideArrayVal2)
转换为大写(或与此相关的任意字符串转换)?
答案 0 :(得分:1)
您可以自己编写递归函数。应该是这样的:
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))