Play: How to remove the fields without value from JSON and create a new JSON with them

僤鯓⒐⒋嵵緔 提交于 2021-01-02 06:37:08

问题


Given the following JSON:

{
  "field1": "value1",
  "field2": "",
  "field3": "value3",
  "field4": ""
}

How do I get two distinct JSONs, one containing the fields with value and another one containing the fields without value? Here below is how the final result should look like:

{
  "field1": "value1",
  "field3": "value3"
}

{
  "field2": "",
  "field4": ""
}

回答1:


You have access to the JSON object's fields as a sequence of (String, JsValue) pairs and you can filter through them. You can filter out the ones with and without value and use the filtered sequences to construct new JsObject objects.

import play.api.libs.json._

val ls =
  ("field1", JsString("value1")) ::
  ("field2", JsString("")) ::
  ("field3", JsString("value3")) ::
  ("field4", JsString("")) ::
  Nil

val js0 = new JsObject(ls)

def withoutValue(v: JsValue) = v match {
  case JsNull => true
  case JsString("") => true
  case _ => false
}

val js1 = JsObject(js0.fields.filterNot(t => withoutValue(t._2)))
val js2 = JsObject(js0.fields.filter(t => withoutValue(t._2)))



回答2:


You can improve @nietaki solution by using partition function.

import play.api.libs.json._

val ls =
  ("field1", JsString("value1")) ::
    ("field2", JsString("")) ::
    ("field3", JsString("value3")) ::
    ("field4", JsString("")) ::
    Nil

val js0 = new JsObject(ls)

def withoutValue(v: JsValue) = v match {
  case JsNull => true
  case JsString("") => true
  case _ => false
}

val (js1, js2) = js0.fields.partition(t => withoutValue(t._2))
JsObject(js1)
JsObject(js2)



回答3:


You can also do it in a one liner:

val (js1, js2) = j.fields.partition(_._2 != JsString(""))
println(JsObject(js1))
println(JsObject(js2))

Code run at Scastie



来源:https://stackoverflow.com/questions/24512942/play-how-to-remove-the-fields-without-value-from-json-and-create-a-new-json-wit

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