简体   繁体   中英

Add/Remove elements in a JSON Array in Scala/Play

I have a pretty complex JSON object that contains, among other things, some JSON arrays that I need to update, removing and adding elements. To do that I'm trying to use a JsPath that point directly to the object inside the array that I need to remove, something like:

/priceLists(1)/sections(0)/items(0)

to remove the element I tried to use json.prune and it doesn't work, I get this error: error.expected.jsobject

Would would be the best way to do that?

Your question is lacking a precise context (ie, structure of your json data), but let's do with what we have.

The error message you get is clear, you can only call prune on a json object, to prune one of its values. You can't use it to prune an element of a json array.

I can only advise you to use json.update, stating that like prune, update only works on json objects. In the body of the update, work on your arrays as you usually do with scala/java data types.

__.json.update(__.reads[JsArray].map { jsArray =>
  val removedElement = JsArray(jsArray.value.filter(_ == ???))
  val addedElement = removedElement :+ JsBoolean(true)
  addedElement
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM