英文:
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
})
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论