0

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?

4
  • What lib are you using for json? Play? Commented May 10, 2017 at 21:09
  • yes, I am using Play framework Commented May 10, 2017 at 21:12
  • 1
    list.foldLeft(Json.obj())(_ deepMerge _) Commented May 10, 2017 at 23:57
  • @cchantep Thanks! If you add your answer then I can accept it. Commented Aug 22, 2017 at 20:48

2 Answers 2

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

This worked perfectly.

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

Sign up to request clarification or add additional context in comments.

Comments

0

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}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.