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

How to clean a json from empty nested objects and empty arrays

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

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