21

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?

djvg
  • 11,722
  • 5
  • 72
  • 103
eabyshev
  • 703
  • 2
  • 8
  • 16
  • According to the [YAML spec (section 1.3)](https://yaml.org/spec/1.2/spec.html), "YAML can therefore be viewed as a natural superset of JSON ...", and "... every JSON file is also a valid YAML file." – djvg Oct 30 '20 at 16:18

7 Answers7

55

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'
markthegrea
  • 3,731
  • 7
  • 55
  • 78
Tanya
  • 666
  • 5
  • 11
5

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"))))'
Sebastian Wagner
  • 2,308
  • 2
  • 25
  • 32
Erik Aronesty
  • 11,620
  • 5
  • 64
  • 44
2

http://jsontoyaml.com/

this website may can help you. It can be used in Bash, JavaScript, JavaScript (browser only), Ruby, Python, Perl, Java..

bystander
  • 551
  • 3
  • 14
  • 4
    I'm against down-voting this. No where in the question it is mentioned as to provide "programmatical way" So this answer also valid. – PasinduJay Jan 15 '18 at 11:49
  • @PasinduJay The tags provide the necessary context - question is tagged Java. – Polygnome Nov 16 '20 at 13:04
1

I'd suggest you consider Data Transformer (disclaimer - I'm its developer). It converts between JSON, YML, and other formats.

You can get it from the Mac App Store or the Microsoft Store.

Geo Systems
  • 101
  • 6
1

yq can be used to convert between JSON and YAML

yq -o yaml --indent 2 --prettyPrint --colors
foo: bar
baz:
  - qux
  - quxx
corge: null
grault: 1
garply: true
waldo: "false"
fred: undefined
emptyArray: []
emptyObject: {}
emptyString: ""

(XML and property files can also be transformed using yq)

jpseng
  • 1,618
  • 6
  • 18
0
function yaml_validate {
  python -c 'import sys, yaml, json; yaml.safe_load(sys.stdin.read())'
}

function yaml2json {
  python -c 'import sys, yaml, json; print(json.dumps(yaml.safe_load(sys.stdin.read())))'
}

function yaml2json_pretty {
  python -c 'import sys, yaml, json; print(json.dumps(yaml.safe_load(sys.stdin.read()), indent=2, sort_keys=False))'
}

function json_validate {
  python -c 'import sys, yaml, json; json.loads(sys.stdin.read())'
}

function json2yaml {
  python -c 'import sys, yaml, json; print(yaml.dump(json.loads(sys.stdin.read())))'
}

More Bash tricks at http://github.com/frgomes/bash-scripts

Richard Gomes
  • 5,675
  • 2
  • 44
  • 50
-4

If you need convert JSONobject to yaml (string). you need. Firstly get json string, then map, after that you can convert to yaml. Here the code:

  // this is your json object
  JSONObject jsonobject = new JSONObject(map);
  // get json string
  String prettyJSONString = jsonobject.toString(4);
  // mapping
  Map<String,Object> map = (Map<String, Object>) yaml.load(prettyJSONString);
  // convert to yaml string (yaml formatted string)
  String output = yaml.dump(map2);
eabyshev
  • 703
  • 2
  • 8
  • 16