arraysjsonscalajson4s

How to add element into a nested array using json4s with Scala


I have the following json String:

  val jsonMessage: String =
    """{
      | "code": "OK",
      | "idEvent": "123",
      | "contract": {
      |     "idApplication": "001"
      | },
      | "version": {
      |     "idVersion": "1",
      |     "entity": [{
      |       "idEntity": "5",
      |       "entityType": [{
      |         "entityNumber": "147",
      |           "entityVersion": [{
      |             "entityCode": "A",
      |             "idCode": "753"
      |           }]
      |       }]
      |     }]
      | }
      |}""".stripMargin

I would like to position a new name field within the entityVersion array using json4s. Any idea how to do this in Scala ?


Solution

  • You can use this code snippet:

    val root = JsonMethods.parse(jsonMessage)
    root.transformField {
      case ("entityVersion", JArray(list)) =>
        val updatedObjects = list.map { case obj: JObject =>
          JObject(obj.obj :+ ("name", JString("Name Value")))
        }
        ("entityVersion", JArray(updatedObjects))
    }