j3d
j3d

Reputation: 9724

PlayFramework: how to transform each element of a JSON array

Given the following JSON...

{
  "values" : [
     "one",
     "two",
     "three"
  ]
}

... how do I transform it like this in Scala/Play?

{
  "values" : [
     { "elem": "one" },
     { "elem": "two" },
     { "elem": "three" }
  ]
}

Upvotes: 3

Views: 2213

Answers (2)

mutantacule
mutantacule

Reputation: 7063

It's easy with Play's JSON Transformers:

val json = Json.parse(
  """{
    |  "somethingOther": 5,
    |  "values" : [
    |     "one",
    |     "two",
    |     "three"
    |  ]
    |}
  """.stripMargin
)

// transform the array of strings to an array of objects
val valuesTransformer = __.read[JsArray].map {
  case JsArray(values) =>
    JsArray(values.map { e => Json.obj("elem" -> e) })
}

// update the "values" field in the original json
val jsonTransformer = (__ \ 'values).json.update(valuesTransformer)

// carry out the transformation
val transformedJson = json.transform(jsonTransformer)

Upvotes: 7

dwickern
dwickern

Reputation: 3519

You can use Play's JSON APIs:

import play.api.libs.json._

val json = Json parse """
    {
      "values" : [
         "one",
         "two",
         "three"
      ]
    }
  """

val newArray = json \ "values" match {
  case JsArray(values) => values.map { v => JsObject(Seq("elem" -> v)) }
}

// or Json.stringify if you don't need readability
val str = Json.prettyPrint(JsObject(Seq("values" -> JsArray(newArray))))

Output:

{
  "values" : [ {
    "elem" : "one"
  }, {
    "elem" : "two"
  }, {
    "elem" : "three"
  } ]
}

Upvotes: 2

Related Questions