Assuming the following json payload
val json = """{
"choices" : [
{
"name" : "A"
},
{
"name" : "B"
},
{
"name" : "C"
},
{
"name" : "D"
}
],
"domain" : "Quizz",
"level" : "Test",
"mandatory": true
}"""
How do I transform it to
val json = """{
"value":"B",
"domain" : "Quizz",
"level" : "Test",
}"""
where the "B" is randomly selected from the available choices ?
This is what I have got so far :
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
This drops the unused "mandatory" field and inserts an empty "value" field. Getting a random value from the array and placing it in "value" escapes me though.
-- edit
I have tried using hcursor which makes the above clearer (to me anyway)
val cursor = parse(json).getOrElse(Json.Null).hcursor
val noMandatory = cursor.downField("mandatory").delete
val withEmptyValue = noMandatory.withFocus(_.deepMerge(Json.obj("value"->Json.Null)))
(I am using circe 0.5.1 in the above examples)