3

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" }
  ]
}

2 Answers 2

7

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)
Sign up to request clarification or add additional context in comments.

Comments

2

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"
  } ]
}

Comments

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.