paul paul - 11 months ago 55
JSON Question

Get JSONArray from JSONObject

I have this json

{"results":[{"a":1,"b":2},{"a":1,"b":2} ]

And I want to have a String json just with the array

[{"a":1,"b":2},{"a":1,"b":2} ]

So far using JSON class from utils, I manage to get the JSONObject, but once that I have the JSONObject does not expose any method to get the JSONArray

val parsed = JSON.parseRaw(source).get
val results = parsed.getJSONArray("key") <-- This is what I was expecting.

Any idea how to get the JSONArray and put it back as String.

Any other library it´s a welcome.


Answer Source

Play Json

To add the dependency to the build.sbt. Add the following line to the library dependencies.

libraryDependencies += ("" %% "play-json" % "2.5.4")

Parse and retrieve array using key results

Json.parse("""{"results":[{"a":1,"b":2},{"a":1,"b":2}]}""") \ "results"

Scala REPL

scala> Json.parse("""{"results":[{"a":1,"b":2},{"a":1,"b":2}]}""") \ "results"
res27: play.api.libs.json.JsLookupResult = JsDefined([{"a":1,"b":2},{"a":1,"b":2}])

Scala REPL

If you want to get the JsArray directly then use as[JsArray]

scala> (Json.parse("""{"results":[{"a":1,"b":2},{"a":1,"b":2}]}""") \ "results").as[JsArray]
res26: play.api.libs.json.JsArray = [{"a":1,"b":2},{"a":1,"b":2}]