繁体   English   中英

使用 Mule 4 dataweave 删除 JSON 消息中所有可能的空格

[英]Remove all posible spaces in JSON message with Mule 4 dataweave

我有一条 JSON 消息,我需要删除所有格式空间以保持值不变。 在对完整负载运行 hash function 之前,这是必需的,因此它需要精确。

我从 Dataweave 编写器配置中的indent=false开始,但我在每个冒号后都有一个空格,如下所示:

{"text": "number\": 1 | array\": [ | number\": 1","number": 1,"array": [1,"as",[],{}]}

在进入 RegEx 世界之前,是否有任何建议的优雅解决方案来删除留下的空格? 如果没有,任何 RegEx 解决方案?

在@SalimKhan(谢谢)建议的帖子之后,我得到了这个解决方案。 基本上我只是在 DataWeave 上写了一个完整的 JSON 自定义编写器。

fun jsonWrite(item) = item match {
    case is Array -> "[" ++ joinBy($ map jsonWrite($), ",") ++ "]"
    case is Object -> "{" ++ joinBy($ pluck ("\"" ++ $$ ++ "\":" ++ 
        ($ match {
            case is String -> "\"" ++ ($ replace "\"" with "\\\"") ++ "\""
            case is Object -> jsonWrite($)
            case is Array -> "[" ++ joinBy($ map jsonWrite($), ",") ++ "]"
            else -> $
        })),",") ++ "}"
    case is String -> "\"" ++ ($ replace "\"" with "\\\"") ++ "\""
    else -> $
}

我尝试使用以下 dw 脚本从 json 中删除所有空间。 下面的代码将在 stream 中给出 json,没有缩进,但每个冒号后会有空格。

%dw 2.0
output application/json indent=false
---
{
    name: "somename",
    city: "sg",
    profession: "tenchdigger"
}

上面脚本的 output 被转换为字符串并使用下面的脚本删除所有空格

%dw 2.0
var someSpaceJson = write(payload, "application/json", {"indent":false}) 
output application/java
---
someSpaceJson replace " " with ""

最终结果是一个没有空格的 json 字符串

"{"name":"somename","city":"sg","profession":"tenchdigger"}"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM