请求编写用于替换字符串特殊字符的Jolt转换规范
实现动态遍历encoding列表的Jolt转换方案
需求说明
遍历输入JSON中的encoding列表,将value字段中所有enc对应的字符替换为对应的dec值:
输入JSON:
[{"value": "My name is-Yash:Jain","encoding": [{"enc": " ","dec": "space"},{"enc": "-","dec": "minus"},{"enc": ":","dec": "colon"}]}]
期望输出:
{"value": "MyspacenamespaceisminusYashcolonJain"}
现有方案的局限
你当前的转换代码通过硬编码split和join步骤实现了三次替换,但这种方式无法动态适配encoding列表的变化——如果列表新增、删除或修改替换规则,必须手动调整转换代码,扩展性较差。
动态适配的Jolt转换规范
以下是可以自动遍历encoding列表、动态应用替换规则的Jolt配置:
[ { "operation": "shift", "spec": { "*": { "value": "originalValue", "encoding": { "*": { "enc": "replacements.&", "dec": "replacements.&" } } } } }, { "operation": "modify-overwrite-beta", "spec": { "currentValue": "@(1,originalValue)", "replacements": { "*": { "$": "=replace(@(3,currentValue), @(1,&), @(1,dec))", "#currentValue": "=replace(@(3,currentValue), @(1,&), @(1,dec))" } } } }, { "operation": "shift", "spec": { "currentValue": "value" } }, { "operation": "remove", "spec": ["originalValue", "replacements"] } ]
步骤解释
- Shift初始化:将原始
value暂存为originalValue,同时把encoding列表中的替换规则转换为replacements下的键值对(enc为键,dec为对应值)。 - 动态替换:初始化
currentValue为原始字符串,遍历replacements中的每一组规则,依次用dec替换currentValue中的enc字符,每次替换后更新currentValue,确保后续替换基于最新结果。 - 提取结果:将最终的
currentValue映射为输出的value字段。 - 清理临时字段:移除转换过程中生成的
originalValue和replacements,保证输出结构简洁。
这个方案无需硬编码任何具体的替换规则,能自动适配encoding列表的变化,通用性更强。
内容的提问来源于stack exchange,提问作者Apoorv Banega Competitive Code
相关产品推荐
相关产品推荐

