【问题标题】:Replacing all JSON String values recursively with Circe用 Circe 递归替换所有 JSON 字符串值
【发布时间】:2019-01-03 12:55:32
【问题描述】:

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

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

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

【问题讨论】:

  • 哦,是的,这会很有帮助!

标签: json scala recursion scala-cats


【解决方案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))

【讨论】:

  • 非常好。它极大地缩短了我的解决方案,所以现在它很简单: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 :_*))(不能在 cmets 中很好地格式化它,但它也可以作为一个单行器)
猜你喜欢
  • 2013-08-21
  • 2011-05-09
  • 2011-09-27
  • 1970-01-01
  • 1970-01-01
  • 2017-04-24
  • 2013-12-29
  • 2019-08-16
  • 2020-06-02
相关资源
最近更新 更多