PGS
PGS

Reputation: 1164

How to iterate over JSValue parsed from JSON String

I have a JSON String ,

val name : String = "["Client_2","tClient_1","Client_NB"]"

I have converted the Json String to JSValue as below using play

val json: JsValue  = Json.parse(cells)

Output of json : ["IotClient_NB_2","IotClient_NB_1","IotClient_NB"]

I need to iterate over above JSON String and take string each value out.

Upvotes: 0

Views: 2200

Answers (1)

andrey.ladniy
andrey.ladniy

Reputation: 1674

The simplest way json.as[List[String]] (throws exception if json is not JsArray of String)

For example

import play.api.libs.json.{JsValue, Json}

val name : String = """["Client_2","tClient_1","Client_NB"]"""
val json: JsValue  = Json.parse(name)
val list = json.as[List[String]]

import play.api.libs.json.{JsValue, Json}

scala> name: String = ["Client_2","tClient_1","Client_NB"]

scala> json: play.api.libs.json.JsValue = ["Client_2","tClient_1","Client_NB"]

scala> list: List[String] = List(Client_2, tClient_1, Client_NB)

Upvotes: 1

Related Questions