get all keys of play.api.libs.json.JsValue

非 Y 不嫁゛ 提交于 2019-12-09 13:01:52

问题


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)

回答1:


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.



来源:https://stackoverflow.com/questions/26650354/get-all-keys-of-play-api-libs-json-jsvalue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!