需要从输入中得到想要的输出——DataWeave

Need to get the desired output from the input - DataWeave

遇到以下情况。任何 guidance/inputs 将不胜感激。

输入负载:

{
    "message": "Bad request :/data/1/actualDelivery expected type: String, found: Null\n
                            /data/1/propertyName expected type: String, found: Null\n
                            /data/1/uniqueID expected type: String, found: Null\n
                            /data/0/amortizationSchedule expected type: String, found: Null\n
                            /data/0/uniqueID expected type: String, found: Null\n
                            /metadata/guid expected type: String, found: Null\n
                            /metadata/partnerName expected type: String, found: Null\n
                            /datasetName expected type: String, found: Null"
}

预期输出:

{
  "datasetName":" expected type: String, found: Null"
  "metadata":{
      "partnerName":" expected type: String, found: Null",
      "guid" : " expected type: String, found: Null"
    },
   "data": [
      {
        "uniqueID" : " expected type: String, found: Null",
        "amortizationSchedule":" expected type: String, found: Null",
      },
      {
        "uniqueID" : " expected type: String, found: Null",
        "propertyName":" expected type: String, found: Null",
        "actualDelivery": " expected type: String, found: Null"
      }
    ]
}

输入中的字段数量可能会有所不同,或者某些字段可能不存在; 数据集、合作伙伴名称、guiid 也有可能不在输入中。在这种情况下,只需要显示可用字段,即

{
      "data": [
          {
            "uniqueID" : " expected type: String, found: Null",
            "amortizationSchedule":" expected type: String, found: Null",
          },
          {
            "uniqueID" : " expected type: String, found: Null",
            "propertyName":" expected type: String, found: Null",
            "actualDelivery": " expected type: String, found: Null"
          }
        ]
}

我已经使用字符串函数来实现子字符串功能。

%dw 2.0
import * from dw::core::Strings
output application/json

var elms = ((substringAfter(payload.message, ":")) splitBy "\n")
var dataElms = elms filter ($ startsWith "/data/")
var metadataElms = elms filter ($ startsWith "/metadata/")
var datasetElms = elms filter ($ startsWith "/datasetName")
var splitDataElms = dataElms distinctBy ($ startsWith "/data/0") map do {
    var dataIndex = "/data/" ++ substringBefore(substringAfter($, "/data/"), "/")
    ---
    (dataElms filter ($ startsWith dataIndex))
}

fun mapElms (elmMap) = elmMap map do {
    var name = substringBefore(substringAfterLast($, "/"), " ")
    var value = substringAfterLast ($, name)
    ---
    (name): value
} reduce ($++$$)

fun isNotEmpty (elm) = not isEmpty(elm)
---
{
    (datasetName: substringAfter(datasetElms[0], "/datasetName")) if (isNotEmpty(datasetElms)),
    (metadata: mapElms(metadataElms)) if (isNotEmpty(metadataElms)),
    data: splitDataElms map (dataElm) -> (mapElms(dataElm))
}