Mule- Mapping key and values to new keys and values

huangapple go评论59阅读模式
英文:

Mule- Mapping key and values to new keys and values

问题

需要从 JSON 中提取键和值,然后生成不同的 JSON 输出。您想要将 "main" 添加到现有的键,并读取所有键。假设在 "properties" 中有 n 个键值对。您可以使用 DataWeave(dwl)脚本来完成这个任务。

以下是一个示例的 DataWeave 脚本,用于将输入 JSON 转换为所需的输出格式:

%dw 2.0
output application/json
fun transformProperty(prop) =
  prop mapObject ((value, key) -> 
    "main$key" : value
  )
---
payload update {
  case properties at .properties -> {
    "properties": transformProperty(properties)
  }
}

您可以将此 DataWeave 脚本用于将输入 JSON 转换为所需的输出格式。这个脚本会将 "main" 添加到 "properties" 中的每个键,并生成相应的输出 JSON。您可以根据需要自定义脚本以适应不同的输入。

英文:

I need to extract key and values from json to form different json output

Input Json

{"somekey":"xyz",
"properties":{
"key1":"value1",
"key2":"value2"
.....
}

Expected Output Json

{"somekey":"xyz",
"properties":{
"mainkey1": "value1"
"mainkey2": "value2"
....
}
}

I need to add "main" to the existing key and read all the keys. Consider there's n number of key value pairs in properties.
How can this be done dwl script?

I tried to map the objects using payload map and write manually the entire keys. As new key value pairs get added i had to write each keys manually into mapping.

答案1

得分: 3

你可以使用update operator来更新父对象。更新将保留现有的键,只更新props对象。要连接属性键,可以使用mapObject。

output application/json
---
payload update {
    case props at .properties -> props mapObject ((value, key) -> {
        ("main" ++ (key as String)): value
    })
}
英文:

You can use update operator to update the parent object. Update will keep the existing keys and only update the props object. To concatenate the property keys a mapObject can be used.

%dw 2.0
output application/json
---
payload update {
    case props at .properties -> props mapObject ((value, key) -> {
        ("main" ++ (key as String)): value
    })
}

huangapple
  • 本文由 发表于 2023年2月13日 22:53:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/75437502.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定