HackerDuck HackerDuck - 4 months ago 24
JSON Question

Transform original Json using Play Framework in Scala

I have the following Json:

{"id": 1,
"url":[
{"format":""},
{"creator":""},
{"value":"http://..."}
]
}


How can I transform it into
"url": "http://..."
.

How can I do this? I tried the following, but it does not seem to be working.

(json \ "value").as[JsString].value

Answer

Because "url" has an array value, you need to index it appropriately to get the value you require, so in your case it would be something like:

scala> val url = (json \ "url")(2).get
url: play.api.libs.json.JsValue = {"value":"http://..."}

scala> (url \ "value").as[String]
res22: String = http://...

I also recommend looking at Argonaut if you are comfortable with a more functional approach for dealing with JSON. It is much superior to the JSON facilities provided by Play.

Comments