Question

Im trying to update json array. If i have JSON like this one:

{
  "value":[
  {
    "name":{
      "first":"Bob",
      "last":"Pegelano"
  },
    "age":31,
    "email":"bob@gmail.com"
  },
  {
    "name":{
      "first":"Majkl",
      "last":"Skot"
    },
    "age":321,
    "email":"gecko@gmail.com"
  }]
}

I can easily update an array like this.

val jsarrayUpdate = (__ \ 'value).json.update(
  __.read[JsArray].map{ o => o :+ Json.obj( "field243" -> "coucou" ) }
)      

myJson.transform(jsarrayUpdate)     

But I have simple array JSON without any key:

  [{
    "name":{
      "first":"Bob",
      "last":"Pegelano"
  },
    "age":31,
    "email":"bob@gmail.com"
  },
  {
    "name":{
      "first":"Majkl",
      "last":"Skot"
    },
    "age":321,
    "email":"gecko@gmail.com"
  }]

And was hoping to be able to edit it with this command:

val jsarrayUpdate2 = __.json.update(
  __.read[JsArray].map{ o => o :+ Json.obj( "field243" -> "coucou" ) }
)  

This is not working nor is anything else I tried in the past two hours. What am I doing wrong?

Thank you.

Was it helpful?

Solution

What about

jsArray.as[List[JsObject]].map {i => i ++ Json.obj( "field243" -> "coucou")}

This will give you a List[JsObject]. If you need you can convert it back to JsArray with

Json.toJson(listOfJsObjects).as[JsArray]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top