我需要对一个 json 对象(不是数组)进行排序,它不是一个简单的键值 相反,它里面有额外的对象
{
"Memo": {
"itemAmount1": "5",
"taxName1": "TAX",
"productPrice1": "10",
"accountName1": "Account Receivable (Debtors)"
},
"Footer": {
"productDescription2": "Maggie",
"itemQuantity2": "49.5",
"accountName2": "Account Receivable (Debtors)",
"taxName2": "TAX"
},
"Header": {
"itemDiscount3": "10",
"accountName3": "Account Receivable (Debtors)",
"productPrice3": "10",
"taxName3": "TAX"
}
}
预期输出是:(也应该对内部对象的键进行排序)
{
"Footer": {
"accountName2": "Account Receivable (Debtors)",
"itemQuantity2": "49.5",
"productDescription2": "Maggie",
"taxName2": "TAX"
},
"Header": {
"accountName3": "Account Receivable (Debtors)",
"itemDiscount3": "10",
"productPrice3": "10",
"taxName3": "TAX"
},
"Memo": {
"accountName1": "Account Receivable (Debtors)",
"itemAmount1": "5",
"productPrice1": "10",
"taxName1": "TAX"
}
}
不一定是 2 级对象层次结构,它可能包含需要排序的 n 级对象层次结构。
这个问题是所问问题的虚拟复制粘贴here(但那是针对javascript而不是dataweave / mule)
内置函数
orderBy()
也可以对对象进行排序。但要对子对象进行排序,您需要一个递归函数,该函数将 orderBy()
应用于按类型匹配的子对象。
%dw 2.0
output application/json
fun sortObjects(x)=
x match {
case o is Object -> o
orderBy ((value, key) -> key)
mapObject (($$): sortObjects($))
else -> $
}
---
sortObjects(payload)
输出:
{
"Footer": {
"accountName2": "Account Receivable (Debtors)",
"itemQuantity2": "49.5",
"productDescription2": "Maggie",
"taxName2": "TAX"
},
"Header": {
"accountName3": "Account Receivable (Debtors)",
"itemDiscount3": "10",
"productPrice3": "10",
"taxName3": "TAX"
},
"Memo": {
"accountName1": "Account Receivable (Debtors)",
"itemAmount1": "5",
"productPrice1": "10",
"taxName1": "TAX"
}
}
请注意,向
Array
添加匹配项,您可以使用该函数同时对数组进行排序。