Given the following JSON...
scala> val js = Json.parse("""{"key1": "value1", "key2": "value2","list":[{"item1": "value1"},{"item2": "value2"}]}""")
js: play.api.libs.json.JsValue = {"key1":"value1","key2":"value2","list":[{"item1":"value1"},{"item2":"value2"}]}
... I get the first element of list
like this:
scala> val l = (js \ "list").as[List[JsValue]]
l: List[play.api.libs.json.JsValue] = List({"item1":"value1"}, {"item2":"value2"})
scala> val first = l(0)
first: play.api.libs.json.JsValue = {"item1":"value1"}
... but how do I remove an element from list
at a given index?
There's nothing in JsValue
nor JsPath
for this, you could use a Lens library such as Monocle. Otherwise, here's one way of doing that:
(js \ "list").get match {
case JsArray(items) => dropAt(items, 1)
}
where dropAt
is:
def dropAt[A](items: Seq[A], id: Int): Seq[A] =
items.zipWithIndex.filter(_._2 != id).map(_._1)
(dropAt
is not pretty but I'm not aware of any nice API for that.)