【问题标题】:Recursive traverse JSON with circe-optics使用 circe-optics 递归遍历 JSON
【发布时间】:2019-08-16 19:41:15
【问题描述】:

我有一个结构复杂的json。像这样的:

{
  "a":"aa",
  "b":"bb",
  "c":[
    "aaa",
    "bbb"
  ],
  "d":{
    "e":"ee",
    "f":"ff"
  }
}

我想将所有字符串值大写。 The Documentation 说:

root.each.string.modify(_.toUpperCase)

但正如预期的那样,只更新了根值。

如何让circe-optics递归遍历所有字符串值?
JSON结构提前未知。

这是 Scastie 上的example


通过 cmets: 我希望所有字符串值都大写,而不仅仅是根值:

{
  "a":"AA",
  "b":"BB",
  "c":[
    "AAA",
    "BBB"
  ],
  "d":{
    "e":"EE",
    "f":"FF"
  }
}

【问题讨论】:

  • 你能显示一下,你想要的数据结果到底是什么。
  • 你的问题不是很清楚。
  • @Rex 更新问题

标签: scala circe


【解决方案1】:

这是一个部分解决方案,例如,它不是完全递归的,但它将解决您示例中 json 的问题:


val level1UpperCase = root.each.string.modify(s => s.toUpperCase)

val level2UpperCase = root.each.each.string.modify(s => s.toUpperCase)
val uppered = (level1UpperCase andThen level2UpperCase)(json.right.get)

【讨论】:

    【解决方案2】:

    以下可能是执行此操作的新方法。为了完整起见,在此处添加它。

      import io.circe.Json
      import io.circe.parser.parse
      import io.circe.optics.JsonOptics._
      import monocle.function.Plated
    
      val json = parse(
        """
          |{
          |  "a":"aa",
          |  "b":"bb",
          |  "c":[
          |    "aaa",
          |    {"k": "asdads"}
          |  ],
          |  "d":{
          |    "e":"ee",
          |    "f":"ff"
          |  }
          |}
          |""".stripMargin).right.get
      val transformed = Plated.transform[Json] { j =>
        j.asString match {
          case Some(s) => Json.fromString(s.toUpperCase)
          case None    => j
        }
      }(json)
    
      println(transformed.spaces2)
    

    给予

    {
      "a" : "AA",
      "b" : "BB",
      "c" : [
        "AAA",
        {
          "k" : "ASDADS"
        }
      ],
      "d" : {
        "e" : "EE",
        "f" : "FF"
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-02-19
      • 2015-05-11
      • 2018-10-06
      • 2016-08-25
      • 2021-10-05
      • 1970-01-01
      • 2018-07-12
      • 2014-03-11
      • 1970-01-01
      相关资源
      最近更新 更多