Update JsObject by adding an element to one of its branches containing an array of numbers

I have JsObjectdynamic content that might look something like this:

{
    "foo": "bar",
    "viewedTaskIds": [1, 2, 3, 4]
}

viewedTaskIds - an array of integers.

What I would like to do is update this JsObjectand add a new number (let 5) to viewTaskIds. I want the result to be JsObject.

How to do this in the Play Framework Scala application (v2.3)?

EDIT . If the branch viewedTaskIdsdoes not exist, it must be created with an array containing only the new number.

+4
source share
2 answers

JSON. , update .

val transformer = (__ \ "viewedTaskIds").json.update(
    __.read[JsArray].map(_.append(JsNumber(5)))
)

, . update Reads[A <: JsValue] . JsArray, map JsNumber(5) .

, , JsValue:

val js = Json.parse("""{
    "foo": "bar",
    "viewedTaskIds": [1, 2, 3, 4]
}""")

scala> js.transform(transformer)
res6: play.api.libs.json.JsResult[play.api.libs.json.JsObject] = JsSuccess({"foo":"bar","viewedTaskIds":[1,2,3,4,5]},/viewedTaskIds)

, , , orElse Reads.pure(JsArray()), , .

val transformer = (__ \ "viewedTaskIds").json.update(
    __.read[JsArray].orElse(Reads.pure(JsArray())).map(_.append(JsNumber(5)))
)

, , . orElse , . - . , , :

val fallback = __.json.update((__ \ "viewedTaskIds").json.put(JsArray(Seq(JsNumber(5)))))

scala> js.transform(transformer).orElse(js.transform(fallback))
res19: play.api.libs.json.JsResult[play.api.libs.json.JsObject] = JsSuccess({"foo":"bar","viewedTaskIds":[5]},)
+4

, update transform. .

, JsObject JsArray. , - JsObject + -, JsArray :+ JsObjects ++:

val model = Json.parse("""{ "foo": "bar", "viewedTaskIds": [1, 2, 3, 4] }""").as[JsObject]
val newIds = (model \ "viewedTaskIds").as[JsArray] :+ JsNumber(5)
val newModel = model - "viewedTaskIds" + ("viewedTaskIds" -> newIds) 
//alternative to using - and +:
val newModel = model ++ Json.obj("viewedTaskIds" -> newIds)

//one liner:
val newModel = model ++ Json.obj("viewedTaskIds" -> ((model \ "viewedTaskIds").as[Seq[Int]] :+ 5))

, (, as[Seq[Int]) , JSON , . , .

0

All Articles