gpt4 book ai didi

json - 如何从空的嵌套对象和空数组中清除 json

转载 作者:行者123 更新时间:2023-12-01 11:29:05 26 4
gpt4 key购买 nike

我有一个嵌套对象,例如:

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

这还不够好。

最佳答案

对您当前的代码稍作修改:

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 - 如何从空的嵌套对象和空数组中清除 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34724764/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com