Leonard Ehrenfried Leonard Ehrenfried - 13 days ago 5
Scala Question

Move JsValue from one place to another in a JsObject

I have the following JSON structure:

{
"id" : "uniqueId",
"foo" : [1,2,3],
"bar": {
"frob" : "quox"
}
}


And I want to transform it to the following one:

{
"id" : "uniqueId",
"bar": {
"frob" : "quox",
"foo-copy" : [1,2,3]
}
}


What is correct play-json transformation to achieve this?

I've tried the following

val moveToObject = (__ \ 'bar ).json.update((__ \ 'foo-copy).json.copyFrom(
(__ \ 'foo).json.pick
))

json.transform(moveToObject).get


But that doesn't give me what I want.

Answer

There is no move transformation, single transformations only (copy + delete). So you need copy foo value to bar\foo-copy and then remove foo:

__.json.update(
  (__ \ "bar" \ "foo-copy").json.copyFrom(
    (__ \ "foo").json.pick
  )
) andThen (__ \ "foo").json.prune

scala> res0: play.api.libs.json.JsResult[play.api.libs.json.JsObject] = JsSuccess({"id":"uniqueId","bar":{"frob":"quox","foo-copy":[1,2,3]}},/foo/foo)