Play [Scala]: How to flatten a JSON object

后端 未结 6 1030
無奈伤痛
無奈伤痛 2021-02-06 13:07

Given the following JSON...

{
  \"metadata\": {
    \"id\": \"1234\",
    \"type\": \"file\",
    \"length\": 395
  }
}

... how do I convert it

6条回答
  •  借酒劲吻你
    2021-02-06 13:39

    Thanks m-z, it is very helpful. (I'm not so familiar with Scala.)

    I'd like to add a line for "flatten" working with primitive JSON array like "{metadata: ["aaa", "bob"]}".

      def flatten(js: JsValue, prefix: String = ""): Seq[JsValue] = {
    
        // JSON primitive array can't convert to JsObject
        if(!js.isInstanceOf[JsObject]) return Seq(Json.obj(prefix -> js))
    
        js.as[JsObject].fieldSet.toSeq.flatMap{ case (key, values) =>
          values match {
            case JsBoolean(x) => Seq(Json.obj(concat(prefix, key) -> x))
            case JsNumber(x) => Seq(Json.obj(concat(prefix, key) -> x))
            case JsString(x) => Seq(Json.obj(concat(prefix, key) -> x))
            case JsArray(seq) => seq.zipWithIndex.flatMap{ case (x, i) => flatten(x, concat(prefix, key + s"[$i]")) }
            case x: JsObject => flatten(x, concat(prefix, key))
            case _ => Seq(Json.obj(concat(prefix, key) -> JsNull))
          }
        }
      }
    

提交回复
热议问题