Geekster
Geekster

Reputation: 491

Flattening a List of nested Json objects in Scala

I have a list of Json Objects in this form:

[{'a': JsonObj()}, {'b':JsonObj()}, .... ]

How do I flatten the list into this form:

{'a': JsonObj(), 'b': JsonObj(), ...}

Note each field has a nested JsonObj as its value. I do not want to flatten those json objects.

I thought of appending it into a empty JsonObj but doesn't work.

val rStreetsJsonObj: JsObject = Json.obj()
for (routeS <- jsonList) {
      rStreetsJsonObj.+(routeS) // Gives error: expected arguments should be of the form (String, jsValue) not JsObject

}

Any ideas?

Upvotes: 0

Views: 1153

Answers (2)

Geekster
Geekster

Reputation: 491

list.foldLeft(Json.obj())(_ deepMerge _)

This worked perfectly.

This answer is from a comment by @cchantep to the original post.

Upvotes: 2

ashburshui
ashburshui

Reputation: 1410

You can have a try this solution:

First: you need convert received string to actual JsArray

the code maybe:

val jsArray = Json.parse("[{\"a\": 1}, {\"b\":1}]").asInstanceOf[JsArray]

Play attention that parse method which return a JsValue type, actual it is a scala trait, the specific implement case class all extend it, such as JsArray

Second: you can iterate the JsArray type, but remember that it has not directly support the foreach method.

But as a case class, you can access it's value method

In one word, the totally solution, you can have try it:

object Test {
  def main(args: Array[String]): Unit = {
    val jsArray = Json.parse("[{\"a\": 1}, {\"b\":1}]").asInstanceOf[JsArray]
    var rStreetsJsonObj: JsObject = Json.obj()

    for (i <- jsArray.value) {
      val tmpObject = i.asInstanceOf[JsObject]
      rStreetsJsonObj = rStreetsJsonObj.++(tmpObject)
    }
    println(rStreetsJsonObj)
  }
}

It will print the result: {"a":1,"b":1}

Upvotes: 0

Related Questions