获取play.api.libs.json.JsValue的所有键 [英] get all keys of play.api.libs.json.JsValue
本文介绍了获取play.api.libs.json.JsValue的所有键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我必须将 play.api.libs.json.JsValue
键存储到列表中。我该怎么办?
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] b $ b
预期
newIndexes = List(3,5,4,2)
解决方案>
如果你想得到json中的所有键,你可以递归使用
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()
}
请注意,订单不会保留为
在中的值是
映射
。
另一个选择是使用 JsObject $ c $中的
Seq
c>代替使用键
:
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]
}
这样你会得到广度优先的json对象中的所有键。
I have to store play.api.libs.json.JsValue
keys to a List. How i do this?
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]()
expecting
newIndexes=List(3,5,4,2)
解决方案
If you want to get all keys in the 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()
}
Note that the order is not preserved as values
in JsObject
is a Map
.
Another option is to use the Seq
of fields in JsObject
instead of using the 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 a breadth-first order of all keys in json object.
这篇关于获取play.api.libs.json.JsValue的所有键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文