Search code examples
jsonscalaarraybuffer

How to create json string from scala ArrayBuffer


I have created a ArrayBuffer from inside for loop. Now I want to create json string out of the same ArrayBuffer

below code i used to create Array buffer val res=new ArrayBuffer[ArrayBuffer[_>:Any]]

`df =
+---+---+
| _1| _2|
+---+---+
|  1|  5|
|  2| 57|
+---+---+



df.collect.foreach(x=> {
  res += ArrayBuffer(x(0), x(1))
})

Need Below json String from above ArrayBuffer dynamically without below hard-codede array values

val str = "head"

val cur  = """{"%s":{"%s":"%s","%s":"%s"}}""".format(str,res(0)(0),res(0)(1),res(1)(0),res(1)(1))

Expected Output should be below as dynamic based on ArrayBuffer size. And column will be 2 but number of rows can increase or decrease.

Array Buffer is like this --> ArrayBuffer(ArrayBuffer(1, 5), ArrayBuffer(2, 57)) 

Expected Json

{"head":{"1":"5","2":"57"}}

Solution

  • I suggest you to use a Json serializer. The easiest one to me is play-json.

    You can add it to your sbt like this:

    libraryDependencies += "com.typesafe.play" %% "play-json" % "2.9.2"
    

    https://mvnrepository.com/artifact/com.typesafe.play/play-json

    Then it's simple as

       // convert to a list of tuple
       val body: ArrayBuffer[(String, JsValue)] = res.map(e => (e.head.toString, Json.toJson(e(1))))
      
       print(Json.toJson(Json.obj({"head" -> JsObject(list)})))
    

    There is more examples here : https://www.playframework.com/documentation/2.8.x/ScalaJson