Leonard Ehrenfried
Leonard Ehrenfried

Reputation: 1613

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.

Upvotes: 1

Views: 119

Answers (1)

andrey.ladniy
andrey.ladniy

Reputation: 1674

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)

Upvotes: 3

Related Questions