1

I'm a newbie to scala/play and I've been trying to update (add a new id to) the query array in the sections[1] of the JSON but I've had no success traversing the JSON as I have little knowledge of transformers and how to use it.


  "definitions": [
    {
      "sections": [
        {
          "priority": 1,
          "content": {
            "title": "Driver",
            "links": [
              {
                "url": "https://blabla.com",
                "text": "See all"
              }
            ]
          },
          "SearchQuery": {
            "options": {
              "aggregate": true,
              "size": 20,
            },
            "query": "{\"id\":{\"include\":[\"0wxZ4Nr2\", \"0wxZbNr2\", \"6WZOPMw1\"}}"
          }
        },
        {
          "priority": 2,
          "content": {
            "title": "Deliver",
            "links": [
              {
                "url": "https://blabla.com",
                "text": "See all"
              }
            ]
          },
          "SearchQuery": {
            "options": {
              "aggregate": true,
              "size": 20,
            },
            "query": "{\"id\":{\"include\":[\"2W12Q2wq\", \"Nwq09lW3\", \"QweNN2d9\"]}}"
          }
        }
  ]
}

Any suggestions on how I can achieve this. My goal is to put values inside the specific fields of JSON array. I am using play JSON library throughout my application?

1
  • It would be good if you could add the code snippet or whatever you have tried. Commented May 12, 2020 at 3:01

1 Answer 1

1

As you noticed if you use PlayJSON you can use Json Transformers

Updating a field would work like this:

val queryUpdater = (__ \ "definitions" \ 1 \ "SearchQuery" \ "query").json.update(
  of[JsString].map {
    case JsString(value) =>
      val newValue: String = ... // calculate new value
      JsString(newValue)
  }
)

json.transform(queryUpdater)

If you needed to update all queries it would be more like:

val updateQuery = (__ \ "SearchQuery" \ "query").json.update(
  of[JsString].map {
    case JsString(value) =>
      val newValue: String = ... // calculate new value
      JsString(newValue)
  }
)

val updateQueries = (__ \ "definitions").json.update(
  of[JsArray].map {
    case JsArray(arr) =>
      JsArray(arr.map(_.transform(updateQuery)))
  }
)

json.transform(updateQueries)
Sign up to request clarification or add additional context in comments.

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.