0

I am using the Play Json Library to parse json in scala and I have a value that looks like this

scala> val extract = (payload \ "id")
extract: play.api.libs.json.JsValue = [8,18]

I want to convert JsValue to Array[Int].

1 Answer 1

2

Well, because, you are working with parsing json - which implies that along with that you need to validate it and properly handle errors, it not so easy just convert it - Play JSON will force you to handle errors. So, answering your question there you can try something like described below:

   val jsonString = "{\"id\": [1, 2, 3] }"
    val payload = Json.parse(jsonString)
    // This will return `JsResult` - success or failure, which need to be properly handled
    println((payload \ "id").validate[Array[Int]].map(_.toList))

    // This is unsafe operation and might throw exception for un-expected JSON
    println((payload \ "id").validate[Array[Int]].get.toList)

which prints out for me next:

JsSuccess(List(1, 2, 3),)
List(1, 2, 3)

I added toList just for output readability. Hope this will help you!

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

4 Comments

Why call .asInstanceOf[JsObject]?
@MarioGalic this was made for sake of simplicity in this example - JsValue is base class describing all the possible json types: primitives, arrays, objects, null etc. In production code it should not be like this off course. Do you thing it is better to refactor this code in another way?
Seems to work without asInstanceOf, for example, Json.parse("""{ "id": [8, 18] }""").\("id").validate[List[Int]]
@MarioGalic Oh, Thank you very much for suggestion - for some reason I thought that this method exists only in JsObject, I'll remove it then. Thank you again for a help!

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.