Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert JSON to YAML. Parsing JSON to YAML

I'm working with configuration files so I need to convert JSON to YAML. For example I have this JSON file:

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

The result should be YAML:

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

Could you help me?

like image 450
eabyshev Avatar asked Oct 07 '14 11:10

eabyshev


2 Answers

You can convert JSON to YAML with two lines of code in Jackson:

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;
    }

}

You will need to add dependencies to Jackson Core, DataBind and DataFormat YAML. Below is a snippet for 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'
like image 111
Tanya Avatar answered Oct 07 '22 11:10

Tanya


Here's a one liner for a file, suitable for sticking in a bash script. This should work on most default pythons on most systems:

python -c 'import json; import yaml; print(yaml.dump(json.load(open("inputfile"))))'
like image 36
Erik Aronesty Avatar answered Oct 07 '22 10:10

Erik Aronesty