Warm tip: This article is reproduced from serverfault.com, please click

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

发布于 2014-07-01 14:35:11

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": ""
}
Questioner
j3d
Viewed
0
nietaki 2014-07-01 23:56:55

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)))