根据过滤器数组过滤 json 负载

Filter json payload based upon filter array

输入负载

{
    "student": {
        "id": 123,
        "class": "seventh",
        "activities": {
            "curriculum" {
                "certification": ["Cyber-security", "Python"],
                "year": [2021, 2021]
            },
            "extra-curriculum": {
                "field": ["volleyball"]
            },
            "others": ["student-forum"]
        }
    }
}

filterList-
"filterList": ["id", "class", "certification", "year", "field", "others"]

预期输出:

{
    "id": 123,
    "class": "seventh",
    "certification": ["Cyber-security", "Python"],
    "year": [2021, 2021]
    "field": ["volleyball"]
    "others": ["student-forum"]
}

这可以通过跟踪密钥来完成,例如:

("year":payload.student.activites.curriculum.year) if( filterList contains "year")

但是当你有巨大的负载时,这是一个非常漫长和无聊的过程。有没有通用的方法来做到这一点?

是的,可以做到。使用递归函数、模式匹配和 filterObject() 函数可以很容易地进行过滤,但是存在隐藏的复杂性。您不仅在过滤,而且还在展平对象层次结构。诀窍是分别进行并合并结果。

%dw 2.0
output application/json
import mergeWith from dw::core::Objects
var filterList=["id", "class", "certification", "year", "field", "others"]

fun subEntries(o, filter)=
    o 
        filterObject ((value, key, index) -> value is Object)
        mapObject ((value, key, index) -> filteKeyRecursive(value, filter) )

fun filteKeyRecursive(x, filter) =
    x match {
        case is Object -> 
            x filterObject ((value, key, index) -> filter contains  (key as String) ) mergeWith subEntries(x, filter)
        else -> x
  }
---
filteKeyRecursive(payload, filterList)

以防万一,如果需要替代递归函数,则可以使用 Descendants selector.PFB 更短的脚本轻松完成。

%dw 2.0
var filterList = ["id", "class", "certification", "year", "field", "others"]
output application/json  
---
(filterList map (v0, k0) -> {
  (v0): (payload.."$(v0)")[0]
}) reduce ((item, obj = {}) -> obj ++ item)

希望对您有所帮助you.Please让我知道。