Playframework - how to update a json indexed element

I am having problem adding json object to array element. This problem has bothered me for quite some time, but I still don't know how to fix it.

I want to add json object to array element, below is the existing json object:

{
  "key1":[ 
          {"key11":"value11"},
          {"key12":"value12"}
         ]
}

      

I want it to be converted with a new json object added:

{
   "key1":[ 
           {"key11":"value11" , "key111":"value111"},
           {"key12":"value12"}
         ]
}

      

Here is my code:

val json = Json.obj( 
         "key1" ->Json.arr(
                        Json.obj("key11" -> "value11"),
                        Json.obj("key12" -> "value12")
         )
)

val transform= (__ \ 'key1 )(0).json.update(  __.read[JsObject].map{ o => o ++ Json.obj( "key111" -> "value111" ) } )

json.validate(transform)

      

But the last line gives below exception. Can anyone give me some advice on how to achieve my goal of adding a json object to an array element?

java.lang.RuntimeException: expected KeyPathNode
at play.api.libs.json.JsPath$.step$1(JsPath.scala:141)
at play.api.libs.json.JsPath$.step$1(JsPath.scala:144)
at play.api.libs.json.JsPath$.play$api$libs$json$JsPath$$buildSubPath$1(JsPath.scala:150)
at play.api.libs.json.JsPath$$anonfun$createObj$1.apply(JsPath.scala:155)
at play.api.libs.json.JsPath$$anonfun$createObj$1.apply(JsPath.scala:153)
at scala.collection.IndexedSeqOptimized$class.foldl(IndexedSeqOptimized.scala:51)
at scala.collection.IndexedSeqOptimized$class.foldLeft(IndexedSeqOptimized.scala:60)
at scala.collection.mutable.WrappedArray.foldLeft(WrappedArray.scala:34)
at play.api.libs.json.JsPath$.createObj(JsPath.scala:153)
at play.api.libs.json.PathReads$$anonfun$jsUpdate$1$$anonfun$apply$15.apply(JsConstraints.scala:81)
at play.api.libs.json.PathReads$$anonfun$jsUpdate$1$$anonfun$apply$15.apply(JsConstraints.scala:81)
at play.api.libs.json.JsResult$class.map(JsResult.scala:73)

      

Thank you for listening

Kirill

+3


source to share


1 answer


You need to select the entire array and convert it to a new array like this:



val transform= (__ \ "key1" ).json.update(
  __.read[JsArray].map { a => 
    JsArray(a.value.updated(0, a(0).as[JsObject] ++ Json.obj("key111" -> "value111")))
  }
)

      

+6


source







All Articles