Get all keys from play.api.libs.json.JsValue
I need to store keys play.api.libs.json.JsValue
in a list. How do I do it?
var str = ??? //json String
val json: JsValue = Json.parse(str)
val data=json.\("data")
println(data) //[{"3":"4"},{"5":"2"},{"4":"5"},{"2":"3"}]
val newIndexes=List[Long]()
pending
newIndexes=List(3,5,4,2)
+3
source to share
1 answer
If you want to get all keys in json, you can do it recursively with
def allKeys(json: JsValue): collection.Set[String] = json match {
case o: JsObject => o.keys ++ o.values.flatMap(allKeys)
case JsArray(as) => as.flatMap(allKeys).toSet
case _ => Set()
}
Please note that the order is not retained, as values
in JsObject
there Map
.
Another option is to use Seq
fields in JsObject
instead of using keys
:
def allKeys(json: JsValue): Seq[String] = json match {
case JsObject(fields) => fields.map(_._1) ++ fields.map(_._2).flatMap(allKeys)
case JsArray(as) => as.flatMap(allKeys)
case _ => Seq.empty[String]
}
This way you will get the first order of all keys in the json object.
+4
source to share