假设以下json有效负载
val json = """{
"choices" : [
{
"name" : "A"
},
{
"name" : "B"
},
{
"name" : "C"
},
{
"name" : "D"
}
],
"domain" : "Quizz",
"level" : "Test",
"mandatory": true
}"""
如何将其转换为
val json = """{
"value":"B",
"domain" : "Quizz",
"level" : "Test",
}"""
" B"是从可用的选择中随机选择的吗?
这是我到目前为止所得到的:
val cursor = parse(json).getOrElse(Json.Null).cursor
for{
noMandatory<- cursor.downField("mandatory").flatMap(_.delete).map(_.top)
withEmptyValue = noMandatory.deepMerge(Json.obj("value"->Json.Null))
}yield withEmptyValue
这会丢弃未使用的&#34;强制性&#34;字段并插入一个空的&#34;值&#34;领域。从数组中获取一个随机值并将其放入&#34; value&#34;但是逃避了我。
- 编辑
我尝试过使用hcursor,这使得上面的内容更清晰(无论如何)
val cursor = parse(json).getOrElse(Json.Null).hcursor
val noMandatory = cursor.downField("mandatory").delete
val withEmptyValue = noMandatory.withFocus(_.deepMerge(Json.obj("value"->Json.Null)))
(我在上面的例子中使用的是0.5.1)
答案 0 :(得分:2)
不要将副作用与纯代码混合使用。所以我没有解决你的随机问题。
其次,我建议不要删除'choices'字段以保持简单。如果你愿意,可以在以后删除该字段。
第三,为简单起见,将获取和转换阶段分开。在这里,您可以使用案例类来完成大部分工作。
我确信这可能不是惯用的Circe解决方案,但它很好Scala:
import io.circe._, io.circe.generic.auto._, io.circe.parser._, io.circe.syntax._
object ChooserApp extends App {
val input =
"""{
"choices" : [
{
"name" : "A"
},
{
"name" : "B"
},
{
"name" : "C"
},
{
"name" : "D"
}
],
"domain" : "Quizz",
"level" : "Test",
"mandatory": true
}"""
val expected =
"""{
"choices" : [
{
"name" : "A"
},
{
"name" : "B"
},
{
"name" : "C"
},
{
"name" : "D"
}
],
"value":"B",
"domain" : "Quizz",
"level" : "Test",
"mandatory": true
}"""
case class ForJson(j: Json) {
def choices: List[String] = {
j.asObject
.toList
.flatMap(_ ("choices"))
.flatMap(_.asArray)
.flatten
.flatMap(_.asObject)
.flatMap(_ ("name"))
.flatMap(_.asString)
}
def chosen(a: String): Json = {
j.asObject
.map(_.add("value", Json.fromString(a)))
.map(Json.fromJsonObject)
.getOrElse(j)
}
}
val expectedList = List("A", "B", "C", "D")
val gotList = ForJson(parse(input).toOption.get).choices
assert(gotList == expectedList, s"Expected $expectedList, got $gotList")
val expectedJson = parse(expected).toOption.get
val gotJson = ForJson(parse(input).toOption.get).chosen("B")
assert(gotJson == expectedJson, s"Expected $expectedJson, got $gotJson")
}
答案 1 :(得分:1)
在挖掘api后,我想出了:
// a couple utilities
def renameKey(srcKey:String,target:String )(obj:JsonObject):Json= {
obj("name").fold(obj)(value => obj.add("value", value).remove("name")).asJson
}
def safeDropKeys(json:Json)(keys:String*):Json=
json.withObject(obj=>keys.foldLeft(obj)((acc, s)=>acc.remove(s)).asJson)
我根据@scala-william建议分离的随机提取器:
def extractRandomChip(cursor: HCursor): Xor[DecodingFailure, Json] = {
val choice = cursor.get[Array[Json]]("choices").map { choices =>
val x = util.Random.nextInt(choices.length)
choices(x).withObject(renameKey("name", "value"))
}
choice
}
然后将它们粘在一起:
val json = for {
initial <- parse(s)
value <- extractRandomChip(initial.hcursor)
cleanedUp = safeDropKeys(initial)("mandatory","choices")
} yield cleanedUp.deepMerge(value)
json.map(_.toString).toOption
根据我对@wheaties回答的评论,我将对两个选项进行基准测试并接受最快选项的结果。
答案 2 :(得分:0)
我的2cents
@ for{
j <- parser.parse(json).toOption
jObj <- j.asObject
jChoices <- jObj("choices")
choices <- jChoices.as[Seq[Map[String,Json]]].toOption
v <- choices(Random.nextInt(choices.size)).get("name")
} yield {
jObj.add("value", v ) .remove("choices")
}
res58: Option[io.circe.JsonObject] = Some(object[domain -> "Quizz",level -> "Test",mandatory -> true,value -> "C"])