Reputation: 803
Using the json API, how can I write a transformer for the following:
{
"name":"John Doe",
"number":22
}
to
{
"name":"John Doe",
"number":22,
"slug":"John-Doe-22"
}
This is doable using string manipulation, but how do I pick the values from the 2 fields and apply that to them?
Upvotes: 2
Views: 797
Reputation: 3441
You can do this:
val json = Json.obj(
"name" -> JsString("John Doe"),
"number" -> JsNumber(22)
)
val transformed =
json.transform(
__.json.update(
(__ \ 'slug).json.put(JsString(
(json \ "name").as[String].replace(' ', '-') + "-" + (json \ "number").as[Int]
))
)
).get
Ok(transformed.toString())
//{"name":"John Doe","number":22,"slug":"John-Doe-22"}
Here is nice post about play json trasformations.
Upvotes: 2