【问题标题】:Modify Existing Json key : Mule修改现有 Json 密钥:Mule
【发布时间】:2018-08-12 02:43:20
【问题描述】:

我的意见

{
  "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 ...
    ]
  }
}

预期输出

{
  "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 ...
    ]
  }
}

我想删除"customItemData"对象键中的"TEMP_",但我不想再次手动重新映射整个JSON对象,一一分配属性。有没有其他选择? DataWeave 中有更短的逻辑吗?我正在使用 Mule 3.9.0。

【问题讨论】:

    标签: mule dataweave


    【解决方案1】:

    这使用递归和模式匹配来遍历数据结构并修改键。如果密钥不包含字符串"TEMP",则保持原样,如果包含,则根据您的要求对其进行修改。

    %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))
    

    请记住使用此类解决方案时的权衡。代码当然不那么冗长,但需要对递归、模式匹配、lambda 和高阶函数等高级概念有深入的了解。

    【讨论】:

    • 感谢@jerney 为您提供解决方案...但是我在执行时遇到异常::default -> $ ^ 没有名为 ':default' 的类型。
    • Abhilash,如果有机会,请再次尝试上述代码。当然没有名为:default 的类型,正确的关键字是default。对任何混淆表示歉意。希望这会有所帮助!
    • 哇...像魅力一样工作...谢谢:D
    猜你喜欢
    • 1970-01-01
    • 2011-01-17
    • 1970-01-01
    • 2014-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多