0

My Input

{
  "Root": {
    "order": [
      {
        "locale": "en-US",
        "orderItems": [
          {
            "product": {
              "partNumber": "23853864"
            },
            "itemSpecifics": {
              "options": {
                "color": "Olive",
                "size": "S"
              },
              "actualPrice": "7",
              "customItemData": {
                "TEMP_8401": "8.95",
                "TEMP_150207": "3.00"
              }
            }
          }
        ]
      }
    ... Large amount of JSON Data ...
    ]
  }
}

Expected output

{
  "Root": {
    "order": [
      {
        "locale": "en-US",
        "orderItems": [
          {
            "product": {
              "partNumber": "23853864"
            },
            "itemSpecifics": {
              "options": {
                "color": "Olive",
                "size": "S"
              },
              "actualPrice": "7",
              "customItemData": {
                "8401": "8.95",
                "150207": "3.00"
              }
            }
          }
        ]
      }
    ... Large amount of JSON Data ...
    ]
  }
}

I want to remove "TEMP_" in the "customItemData" object keys, but I don't want to manually remap the entire JSON object again, assigning properties one by one. Is there any alternative? Any shorter logic in DataWeave? I'm using Mule 3.9.0.

jerney
  • 2,187
  • 1
  • 19
  • 31

1 Answers1

0

This uses recursion and pattern matching to walk through the data structure and modify the keys. If the key doesn't contain the string "TEMP" it leaves it as is, if it does, it modifies it according to your requirements.

%dw 1.0
%output application/json

%function applyToKeys(e, fn)
  e match {
    :array  -> $ map ((v) -> applyToKeys(v, fn)),
    :object -> $ mapObject ((v, k) -> {(fn(k)): applyToKeys(v, fn)}),
    default -> $
  }
---
applyToKeys(payload,
            ((key) -> ((key as :string) splitBy "_" )[1] 
                      when ((key as :string) contains "TEMP")
                      otherwise key))

Please keep in mind the tradeoffs when using a solution like this. The code is certainly less verbose, but it requires a solid understanding of advanced concepts like recursion, pattern matching, lambdas, and higher order functions.

jerney
  • 2,187
  • 1
  • 19
  • 31