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

前端 未结 1 1616
感情败类
感情败类 2021-02-15 23:37

I have to store play.api.libs.json.JsValue keys to a List. How i do this?

var str = ???                        //json String
val json: JsValue = Jso         


        
相关标签:
1条回答
  • 2021-02-16 00:17

    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.

    0 讨论(0)
提交回复
热议问题