我正在尝试使用 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)
但我在教程中没有看到 eachArrayItem
或 eachObjectValue
的任何定义。
最佳答案
正确的语法是
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/