[play/scala] How to create and fill a JsArray with play-json transformer

8 views
Skip to first unread message

Christophe

unread,
Feb 16, 2017, 4:14:50 PM2/16/17
to Play Framework

With Play/Scala, I try to transform this json:


val json = Json.parse(""" 
{
  "name": "John Doe",
  "location": { 
    "lon": 48.858596, 
    "lat": 2.294481 
  }
} 
""")


into this result:


val result = Json.parse(""" 
{ 
  "name": "John Doe", 
  "location": { 
    "type": "Point", 
    "coordinates": [48.858596, 2.294481] 
  }
} 
""")


Any idea how to apply the magic? Here's what i tried:


import play.api.libs.json._
import play.api.libs.json.Reads._
import play.api.libs.functional.syntax._

val transformer = {
    val lon = (locationField \ "lon").json.pick
    val lat = (locationField \ "lat").json.pick

    __.json.update((
        (locationField \ "type").json.put( JsString("Point") ) and
        (locationField \ "coordinates").json.put( JsArray() )).reduce
      andThen
        (locationField \ "coordinates").json.update(of[JsArray].map { // How to add lon/lat into JsArray?????
          case JsArray(arr) => JsArray(arr :+ JsNumber(3L))
          }
        )
      andThen (
        (locationField \ "lon").json.prune and
        (locationField \ "lat").json.prune).reduce
    )
  }

json.transform(transformer)


The original post from StackOverflow.

Get the code on Gist.


Thanks.


Christophe

Reply all
Reply to author
Forward
0 new messages