0

I'm working with this kind of Json in Scala :

{
    "ClientBase": [
        {
          "string#name": "robert",
          "int#age": 46,
          "string#country": "USA"
        },
        {
          "string#name": "tom",
          "int#age": 45,
          "string#country": "UK"
        }
    ]
}

I use Json4s library and I would like to add a new field to each client. I know how do this for one but is there a quick way to do this for every one ?

I would like a result like this :

{
    "ClientBase": [
        {
          "string#name": "robert",
          "int#age": 46,
          "string#country": "USA",
          "BLOCK_ID" : "client_base"
        },
        {
          "string#name": "tom",
          "int#age": 45,
          "string#country": "UK",
          "BLOCK_ID" : "client_base"
        }
    ]
}

2 Answers2

0

Can you not just map over them all using your Json -> Json function that adds it to one? Something like:

val withBlock = parse(withoutBlock).extract[List[Clients]] map addBlock

Or am I not understanding the question?

andyczerwonka
  • 4,230
  • 5
  • 34
  • 57
0

Here is an approach using scala.util.parsing.json

  import scala.util.parsing.json.JSON
  val string =
  """{
  |    "ClientBase": [
  |        {
  |          "string#name": "robert",
  |          "int#age": 46,
  |          "string#country": "USA"
  |        },
  |        {
  |          "string#name": "tom",
  |          "int#age": 45,
  |          "string#country": "UK"
  |        }
  |    ]
  |}
""".stripMargin

val start = """"{"ClientBase":[{"""
val end = """}]}"""
val json = JSON.parseFull(string) match {
      case Some(e) =>
            val clientBase = e.asInstanceOf[Map[String,Any]]
                 .getOrElse("ClientBase", List[Map[String,Any]]())
            val list = clientBase.asInstanceOf[List[Map[String, Any]]]
            val result = list.map(e=> e.+("BLOCK_ID" -> "client_base"))
            result.mkString(start, ",", end)
      case None => string
}
print(json)
//"{"ClientBase":[{Map(string#name -> robert, int#age -> 46.0, string#country -> USA, BLOCK_ID -> client_base),Map(string#name -> tom, int#age -> 45.0, string#country -> UK, BLOCK_ID -> client_base)}]}

Hope this is a helpful.

Puneeth Reddy V
  • 1,538
  • 13
  • 28