简体   繁体   English

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

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

I have a JSON message where I need to remove all format spaces keeping values untouched.我有一条 JSON 消息,我需要删除所有格式空间以保持值不变。 This is required before running a hash function over the full payload so it needs to be precise.在对完整负载运行 hash function 之前,这是必需的,因此它需要精确。

I started with the indent=false in the Dataweave writer configuration but I got a space after each colon like this:我从 Dataweave 编写器配置中的indent=false开始,但我在每个冒号后都有一个空格,如下所示:

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

Any suggested elegant solution to remove the spaces left before entering in the RegEx world?在进入 RegEx 世界之前,是否有任何建议的优雅解决方案来删除留下的空格? If not, any RegEx solution?如果没有,任何 RegEx 解决方案?

I have got this solution following @SalimKhan (thanks for that.) suggested post.在@SalimKhan(谢谢)建议的帖子之后,我得到了这个解决方案。 Basically I just wrote a full JSON custom writer on DataWeave.基本上我只是在 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 -> $
}

I tried to remove all space from a json using below dw scripts.我尝试使用以下 dw 脚本从 json 中删除所有空间。 The below one will give json in a stream with no indent, but there will be space after each colon.下面的代码将在 stream 中给出 json,没有缩进,但每个冒号后会有空格。

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

The output of above script is converted to string and all spaces are removed using below script上面脚本的 output 被转换为字符串并使用下面的脚本删除所有空格

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

The end result is a json string with no space最终结果是一个没有空格的 json 字符串

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

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

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