将 JSON 转换为 YAML。将 JSON 解析为 YAML

2022-09-02 11:22:13

我正在使用配置文件,因此我需要将JSON转换为YAML。例如,我有这个JSON文件:

{
  "foo": "bar",
  "baz": [ "qux","quxx"],
  "corge": null,
  "grault": 1,
  "garply": true,
  "waldo": "false",
  "fred": "undefined",
  "emptyArray": [],
  "emptyObject": {},
  "emptyString": ""
}

结果应该是 YAML:

foo: "bar"
baz: 
  - "qux"
  - "quxx"
corge: null
grault: 1
garply: true
waldo: "false"
fred: "undefined"
emptyArray: []
emptyObject: {}
emptyString: ""

你能帮我吗?


答案 1

您可以在 Jackson 中使用两行代码将 JSON 转换为 YAML:

import java.io.IOException;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLMapper;

public class Library {

    public String asYaml(String jsonString) throws JsonProcessingException, IOException {
        // parse JSON
        JsonNode jsonNodeTree = new ObjectMapper().readTree(jsonString);
        // save it as YAML
        String jsonAsYaml = new YAMLMapper().writeValueAsString(jsonNodeTree);
        return jsonAsYaml;
    }

}

您需要向 Jackson Core、DataBind 和 DataFormat YAML 添加依赖项。以下是 Gradle 的片段:

compile 'com.fasterxml.jackson.core:jackson-core:2.8.6'
compile 'com.fasterxml.jackson.core:jackson-databind:2.8.6'
compile 'com.fasterxml.jackson.dataformat:jackson-dataformat-yaml:2.8.6'

答案 2

这是一个文件的一个衬里,适合粘贴在bash脚本中。这应该适用于大多数系统上的大多数默认python:

python -c 'import json; import yaml; print(yaml.dump(json.load(open("inputfile"))))'