播放:如何从JSON中删除无值的字段并使用它们创建新的JSON [英] Play: How to remove the fields without value from JSON and create a new JSON with them

查看:91
本文介绍了播放:如何从JSON中删除无值的字段并使用它们创建新的JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下JSON:

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

如何获取两个不同的JSON,一个包含带值的字段,另一个包含不带值的字段?下面是最终结果的样子:

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": ""
}

推荐答案

您可以按(String, JsValue)对的顺序访问JSON对象的字段,并且可以对它们进行过滤.您可以过滤掉有和没有值的对象,并使用过滤后的序列构造新的JsObject对象.

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

这篇关于播放:如何从JSON中删除无值的字段并使用它们创建新的JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆