gpt4 book ai didi

json - 如何通过 Circe 修改 json 的值类型

转载 作者:行者123 更新时间:2023-12-02 09:21:51 25 4
gpt4 key购买 nike

我需要捕获一个json的int值,并通过某个映射表将其转换为一个字符串值。我使用 circe,我知道如何在不更改值类型的情况下修改值,例如:

package com.accenture.soh.driver

import io.circe._, io.circe.parser._
import cats.syntax.either._
import io.circe._, io.circe.parser._
import io.circe.optics.JsonPath._

/**
* Created by laurence.geng on 2017/2/2.
*/
object CirceTest extends App {

val json: Json = parse(
"""
[
{
"metric":"my-metric",
"dps":{"1484214238":5,"1484214239":1,"1484214240":4,"1484214241":11}
}
]
""").getOrElse(Json.Null)

val doubleValue: Json => Json = root.each.dps.each.int.modify(_ * 2)

println(doubleValue(json).toString())

}

输出是:

[
{
"metric" : "my-metric",
"dps" : {
"1484214238" : 10,
"1484214239" : 2,
"1484214240" : 8,
"1484214241" : 22
}
}
]

但是,实际上,我需要做的是将 int 值更改为某个字符串值,即 1 -> "A"、2 -> "B",等等,问题是:"modify"方法只接受一个返回相同类型的输入值的函数,所以,我不能编码如下:

val intToString: Json => Json = root.each.dps.each.int.modify(_.toString)

我的预期输出可能如下所示:

[
{
"metric" : "my-metric",
"dps" : {
"1484214238" : "10",
"1484214239" : "2",
"1484214240" : "8",
"1484214241" : "22"
}
}
]

谁能给我一个解决方案(基于 Circe)?

最佳答案

您可以使用圆游标来完成它,但我认为仅转换为案例类并对其进行操作会更容易。

 val json =
"""
|{
| "metric":"my-metric",
| "dps":{"1484214238":5,"1484214239":1,"1484214240":4,"1484214241":11}
| }
""".stripMargin

val doc = parse(json).getOrElse(Json.Null)
val cursor = doc.hcursor
val dps = cursor.downField("dps")
val result = dps.withFocus { json: Json =>
json.mapObject { jsonObject =>
JsonObject.fromMap(jsonObject.toMap.mapValues { x =>
Json.fromString(x.asNumber.get.toString)
})
}
}

关于json - 如何通过 Circe 修改 json 的值类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41997983/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com