我有一个输入json,如下所示:
{
"dashboard": {
"id": 0,
"originalTitle": "Test dashboard",
"rows": [
{
"collapse": false,
"editable": true,
"height": "250px",
"panels": [],
"title": "Row"
}
],
"schemaVersion": 0,
"tags": [
"T35T-DA5H-80ARD"
],
"timezone": "browser",
"title": "Test dashboard",
"version": 0
},
"overwrite": true
}
我想通过向列表中添加元素来更新“面板”字段。我现在能做的就是选择“面板”的价值:
val json = Json.parse(dashboardJson).validate[JsObject].get
json.transform(
(__ \ 'dashboard).json.pickBranch
(
(__ \ 'rows).json.pickBranch
(
(__ \\ 'panels).json.pick
)
)
)
这导致:
JsSuccess({"dashboard":{"rows":[]}},/dashboard/rows//panels)
但是当我尝试像这样更新它时,它不起作用:
json.transform(
(__ \ 'dashboard).json.pickBranch
(
(__ \ 'rows).json.pickBranch
(
(__ \\ 'panels).json.update
(
__.read[JsObject].map { o => o ++ Json.obj( "bla" -> "blabla" ) }
)
)
)
)
这导致:
JsError(List((/dashboard/rows,List(ValidationError(List(error.expected.jsobject),WrappedArray())))))
知道我做错了吗?
答案 0 :(得分:1)
您必须遍历每个JsArray
(行和面板):
import play.api.libs.functional.syntax._
import play.api.libs.json.Json._
import play.api.libs.json.Reads._
import play.api.libs.json._
val t = (
(__ \ "dashboard" \ "rows").json.update(
of[JsArray](
list(
(__ \ "panels").json.update(
of[JsArray].map{ case JsArray(arr) => JsArray(arr :+ JsString("sss"))}
)
).map(JsArray)
)
)
)
json.transform(t)
scala> JsSuccess({
"dashboard": {
"id": 0,
"originalTitle": "Test dashboard",
"rows": [
{
"collapse": false,
"editable": true,
"height": "250px",
"panels": [
"sss"
],
"title": "Row"
}
],
"schemaVersion": 0,
"tags": [
"T35T-DA5H-80ARD"
],
"timezone": "browser",
"title": "Test dashboard",
"version": 0
},
"overwrite": true
},/dashboard/rows)