You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过命令行将层级YAML转点分隔键JSON?Jackson可行吗?

将层级YAML转换为点分隔键的JSON:命令行与Jackson实现方案

一、命令行工具实现(推荐yq)

用yq(mikefarah维护的版本,区别于Python版yq)可以快速完成转换,步骤如下:

  1. 确保已安装新版yq
  2. 执行转换命令:
yq eval -o=json --flat '.' input.yaml > output.json

参数说明:

  • -o=json:指定输出格式为JSON
  • --flat:自动将YAML的层级结构拍平,用点连接嵌套键
  • .:表示处理整个YAML文档
  • input.yaml为源YAML文件,output.json是输出的目标JSON文件

如果用的是旧版yq,可尝试yq r --tojson --flat input.yaml,但建议升级到最新版,功能更稳定。

二、Jackson实现(Java代码)

Jackson完全可以实现这个转换,核心逻辑是先把YAML解析成嵌套Map,再递归遍历Map拼接点分隔键,最后序列化为JSON。

1. 依赖配置(Maven)

需要引入Jackson的databind和yaml模块:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.15.2</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-yaml</artifactId>
    <version>2.15.2</version>
</dependency>

2. 实现代码

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import java.io.File;
import java.util.HashMap;
import java.util.Map;

public class YamlToFlatJsonConverter {
    public static void main(String[] args) throws Exception {
        // 读取YAML文件为嵌套Map
        ObjectMapper yamlReader = new ObjectMapper(new YAMLFactory());
        Map<String, Object> nestedMap = yamlReader.readValue(new File("input.yaml"), Map.class);

        // 扁平化嵌套Map
        Map<String, Object> flatMap = new HashMap<>();
        flattenNestedMap(nestedMap, "", flatMap);

        // 将扁平化Map写入JSON文件
        ObjectMapper jsonWriter = new ObjectMapper();
        jsonWriter.writerWithDefaultPrettyPrinter().writeValue(new File("output.json"), flatMap);
    }

    private static void flattenNestedMap(Map<String, Object> input, String currentKey, Map<String, Object> result) {
        for (Map.Entry<String, Object> entry : input.entrySet()) {
            String newKey = currentKey.isEmpty() ? entry.getKey() : currentKey + "." + entry.getKey();
            if (entry.getValue() instanceof Map) {
                // 递归处理嵌套的子Map
                flattenNestedMap((Map<String, Object>) entry.getValue(), newKey, result);
            } else {
                // 非嵌套值直接存入结果Map
                result.put(newKey, entry.getValue());
            }
        }
    }
}

补充说明

如果你的YAML包含数组结构,上面的代码暂不支持处理。若需支持数组,可在递归逻辑中判断值是否为集合,给每个元素添加索引后缀(比如parentKey.0、parentKey.1),具体逻辑可根据需求调整。

内容的提问来源于stack exchange,提问作者Justo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 08:15:46