【问题标题】:How to clean a json from empty nested objects and empty arrays如何从空嵌套对象和空数组中清除 json
【发布时间】: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"
  }
}

这还不够好。

【问题讨论】:

  • 创建一个新对象,只复制你想要的内容?

标签: json scala playframework playframework-2.0


【解决方案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
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-05
    • 1970-01-01
    • 2021-12-13
    • 2019-04-25
    • 1970-01-01
    相关资源
    最近更新 更多