如何从空嵌套对象和空数组中清除 json
Posted
技术标签:
【中文标题】如何从空嵌套对象和空数组中清除 json【英文标题】:How to clean a json from empty nested objects and empty arrays 【发布时间】:2016-04-15 22:51:44 【问题描述】:我有一个嵌套对象,例如:
"name:"ABC",
"nest1":
"field1": null,
"field2": null,
"field3": [],
"field4": ,
,
"nest2":
"field1":"123",
"field2":null
我想清理这个 json,并确保输出是:
"name:"ABC",
"nest2":
"field1":"123"
我写了以下代码:
def withoutNullAndEmptyObj(json: JsValue): JsValue =
json match
case JsObject(fields) =>
if (fields.isEmpty) JsNull
else
fields.foldLeft(new JsObject(Map()))((agg, field) =>
field match
case (_, JsNull) => agg
case other@(name, value: JsArray) => if (value == emptyArray) agg else agg+other
case (name, value: JsObject) => if (value == emptyObject) agg else agg+(name, withoutNullAndEmptyObj(value))
case other@(name, value) => agg+other
)
case other => other
问题是它不能完全工作。 它将产生以下json:
"name:"ABC",
"nest1":,
"nest2":
"field1":"123"
这还不够好。
【问题讨论】:
创建一个新对象,只复制你想要的内容? 【参考方案1】:对您当前的代码稍作修改:
def withoutNullAndEmptyObj(json: JsValue): JsValue =
json match
case JsObject(fields) =>
if (fields.isEmpty) JsNull
else
fields.foldLeft(new JsObject(Map()))((agg, field) =>
field match
case (_, JsNull) => agg
case other @ (name, value: JsArray) => if (value == emptyArray) agg else agg + other
case (name, value: JsObject) =>
if (value == emptyObject) agg
else
//added further check on else part.
val nested = withoutNullAndEmptyObj(value);
if (nested == emptyObject)
agg
else
agg + (name, nested)
case other @ (name, value) => agg + other
)
case other => other
【讨论】:
以上是关于如何从空嵌套对象和空数组中清除 json的主要内容,如果未能解决你的问题,请参考以下文章