使用 YamlBuilder 将 Map<String, List<String>> 转换为 Yaml

Convert Map<String, List<String>> to Yaml using YamlBuilder

我想转换一个json

{“测试”:“1,2,3,4”}

进入以下形式的 yaml:

---
test:
  - 1
  - 2
  - 3
  - 4

为此,我尝试使用以下 groovy 片段:

def json = new groovy.json.JsonSlurper().parseText('{"test": "1,2,3,4"}')
println json
def ymlMap = json.collectEntries { k, v -> [k , v.split(', ')] }
def yml = new groovy.yaml.YamlBuilder()
yml ymlMap
println yml.toString()

但它打印

---
test:
- "1,2,3,4"

有任何正确使用 yamlbuilder 的提示吗?

哈哈,你的split-regex包含一个space太多了:

json.collectEntries { k, v -> [k , v.split(',')] }

然后打印:

---
test:
- "1"
- "2"
- "3"
- "4"

在 space 到位后,该值不会拆分并输出 as-is。