Search code examples
jsonscalaplay-json

How to convert nested Json String to Json struct in play json


I am trying to use play json library update method to convert nested json string to Json struct. But I am not able to get syntax correct. can someone please help me with this? I am using update method in https://www.playframework.com/documentation/2.5.x/ScalaJsonTransformers

Ex: I have sample input json

{
    "key1": "value",
    "key2": {
        "key3": {
            "key4": "{\"value1\":100, \"value2\":200}"
        }
    }
}

The expected output should be:

{
    "key1": "value",
    "key2": {
        "key3": {
            "key4": {"value1":100, "value2":200}
        }
    }
}

Solution

  • Please see How to update a nested json using scala play framework? for the documentation of update. In your case, let's assume that the json string is stored at jsonString, so we parse it:

    val json = Json.parse(jsonString)
    

    Now we need to define a reader, that will know to convert the string at path __ \ "key2" \ "key3" \ "key4" into a JsObject, and remain all other fields the same. So we declare such a reader:

    val jsPath = JsPath \ "key2" \ "key3" \ "key4"
    implicit val reads: Reads[JsObject] = jsPath.json.update(__.read[JsString].map{o => Json.parse(o.value)})
    

    Then the usage is pretty easy:

    val result = json.validate[JsObject] match {
      case JsSuccess(value, _) =>
        println(value)
      case JsError(errors) =>
        println(errors)
    }
    

    Code run at Scastie.