0
import play.api.libs.json._
import scala.util.parsing.json.{JSON, JSONArray, JSONObject}

I have following json array-

 val groupNameList = Json.arr(
    Json.obj(
      "groupName" -> "All",
      "maxSeverity" -> allGroupSeverityCount,
      "hostCount" -> (windowsCount + linuxCount + esxCount + networkCount + storageCount + awsLinuxCount + awsWindowsCount)),
    Json.obj(
      "groupName" -> "Private",
      "maxSeverity" -> privateGroupSeverityCount,
      "hostCount" -> (windowsCount + linuxCount + esxCount + networkCount + storageCount)),
    Json.obj(
      "groupName" -> "Public",
      "maxSeverity" -> publicGroupSeverityCount,
      "hostCount" -> (awsLinuxCount + awsWindowsCount))
   )

I want to append a following list of json objects to this array -

List({"groupName" : "group1", "maxSeverity" : 10, "hostCount" : 1, "members" : ["192.168.20.30", "192.168.20.31", "192.168.20.53", "192.168.20.50"]})

I want to merge list into array.

How do I append given list to json array using scala???

6
  • What library is this using? Commented Oct 21, 2014 at 4:57
  • @ Martin - I added import statements in my edit. please refer Commented Oct 21, 2014 at 5:13
  • In the last snippet where you show the data that you want to append, what is the type of that expression? It looks like an odd combination of Scala and JSON. It is a List[String]? List[JsArray]? Commented Oct 21, 2014 at 5:20
  • It is List[JSONObject] Commented Oct 21, 2014 at 5:32
  • Ah, so you're trying to convert JS objects from Scala's parser combinators library to JS objects in Play! The question makes sense now. Commented Oct 21, 2014 at 5:42

1 Answer 1

1

The easiest (though probably not most efficient) way to convert an object between types of different JSON libraries is via its JSON string representation.

(o: JSONObject => Json.parse(o.toString()))

Once you have a List[JsObject], you can pass it into the JsArray constructor and then use ++ to concatenate the two JsArrays.

Putting it together in an example:

import play.api.libs.json.{Json, JsArray}
import scala.util.parsing.json.JSONObject

object Foo {

  val jsArray = Json.arr(
    Json.obj("a" -> "b", "c" -> 2),
    Json.obj("d" -> "e", "f" -> 3))

  val list = List(
    JSONObject(Map("g" -> "h", "i" -> 4)),
    JSONObject(Map("j" -> "k", "m" -> 5))
  )

  def main(args: Array[String]): Unit = {
    println(jsArray ++ JsArray(list.map(o => Json.parse(o.toString()))))
    // [{"a":"b","c":2},{"d":"e","f":3},{"g":"h","i":4},{"j":"k","m":5}]
  }
}
Sign up to request clarification or add additional context in comments.

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.