json - 使用 Circe 光学器件修改对象的所有字段或数组的所有项目

标签 json scala circe

我正在尝试使用 Circe's optics 修改嵌套 JSON 结构。但是,所有示例仅修改对象中具有已知名称的单个字段。

我需要做什么:

  • 假设我的对象的 foo 键包含一个对象数组,则递增每个对象中的 counter 键。
  • 假设我的对象的 bar 键包含一个对象,则增加映射到该对象中每个键的值中的 counter 键。
  • 保持对象中所有其他值不变。

示例:

{
  "foo": [
    {
      "counter": 1
    },
    {
      "counter": 2
    }
  ],
  "bar": {
    "three": {
      "counter": 3
    },
    "four": {
      "counter": 4
    }
  }
}

应该变成

{
  "foo": [
    {
      "counter": 2
    },
    {
      "counter": 3
    }
  ],
  "bar": {
    "three": {
      "counter": 4
    },
    "four": {
      "counter": 5
    }
  }
}

当对象及其成员的类型不符合我的预期时,行为并不重要。

我期望这样的事情:

val incrementCounterArray: Json => Json =
    root.foo.eachArrayItem.counter.modify(_ + 1)
val incrementCounterObject: Json => Json =
    root.bar.eachObjectValue.counter.modify(_ + 1)

但我在教程中没有看到 eachArrayItemeachObjectValue 的任何定义。

最佳答案

正确的语法是

val incrementCounterArray: Json => Json =
  root.foo.each.counter.int.modify(_ + 1)

val incrementCounterObject: Json => Json =
  root.bar.each.counter.int.modify(_ + 1)

看看官方的例子circe-optics documentation了解更多详情:

关于json - 使用 Circe 光学器件修改对象的所有字段或数组的所有项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56729611/

相关文章:

json - Powershell Invoke-RestMethod返回JSON

javascript - select2从本地json文件加载数据

scala - 如何通过 Scala 中的 Play Framework 2.5 流式传输压缩文件(即时)?

scala - 在 Scala 中定义 ADT 的最佳方式是什么 - OO vs FP

scala - 如何在 Scala 中的语句之间等待 N 秒?

scala - 当字段不完整时用 Circe 解码 Json

json - 在 Scala 中使用 circe 解码结构化 JSON 数组

json - 使用 circe 预处理点符号样式字段

java - 寻找一种解析多类型 JSON 字段的方法

python - 如何限制 JSONEncoder 产生的 float ?