2

Suppose I have a json array that looks like this (I receive it from a remote service):

[{"id": 1}, {"id": 2}, ... , {"id": 10}]

And, say, I want to 'transform' it like this (add 100 to 'id's and other values):

[{"id": 101}, {"id": 102}, ..., {"id": 110} ]

As for starters I wanted to 'update' it so that it would at least replace the initial array with a blank one (just to test how stuff works).

Json.parse("""[{"id": 1}, {"id": 2}]""").transform( (__).json.update( __.read[JsArray].map(_ => JsArray()) ))

But it throws an exception:

play.api.libs.json.JsResult[play.api.libs.json.JsObject] = JsError(List((,List(ValidationError(List(error.expected.jsobject),WrappedArray())))))

However if they are sealed inside of a json object then it kinda works:

Json.parse("""{"ids": [{"id": 1}, {"id": 2}]}""").transform( (__ \ "ids").json.update( __.read[JsArray].map(_ => JsArray()) ))

which results in

play.api.libs.json.JsResult[play.api.libs.json.JsObject] = JsSuccess({"ids":[]},/ids)

How do I deal with array json? Thanks in advance

1 Answer 1

4

Try the following code,

case class ID(id: Int)
implicit val reads = Json.reads[ID]

Json.parse("""[{"id": 1}, {"id": 2}]""").as[JsArray].value.map(_.transform(__.json.update {
  __.read[ID].map { case x: ID => Json.obj("id" -> (x.id + 100)) }
}))
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! But what if I want to output it to the user's browser? It seems that I cannot just pass it to "Ok(...)" as it is not "Writable".
Why not ask this as a separate question?
Seems reasonable! Thank you for your help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.