Category Archives: YAML

YAML and JAVA Configuration

Below are Tools which support YAML for JAVA API’s. Here I will focus only on SnakeYAML which widely used by industry.

  • JvYaml
  • SnakeYAML
  • YamlBeans
  • JYaml
  • Camel

SnakeYAML Configuration

JAVA


<dependency>
    <groupId>org.yaml</groupId>
    <artifactId>snakeyaml</artifactId>
    <version>1.20-SNAPSHOT</version>
  </dependency>

Android


<dependency>
  <groupId>org.yaml</groupId>
  <artifactId>snakeyaml</artifactId>
  <version>1.20-SNAPSHOT</version>
  <classifier>android</classifier>
</dependency>

For any operation with SnakeYAML api’s you have to use below steps:
package :

org.yaml.snakeyaml.Yaml

Intialization:
Yaml yaml = new Yaml();

Loading YAML :

  • yaml.load(String) accepts a String.
  • yaml.load(InputStream) accepts a InputStream.

yaml.load(InputStream) detects the encoding by checking the BOM (byte order mark) sequence at the beginning of streams. If no BOM presents the utf-8 encoding is assumed..

More

To know more about YAML Syntax, Configuration with Java and other supporting language, frameworks and tools, Sample configuration files and JSON and YAML conversion follow below YAML Tutorials and YAML related exceptions follow YAML Issues.

Advertisements

JAVA : How to convert YAML Documents to JSON List?

Here is code to convert YAML documents to JSON objects by Jackson and snakeyml apis. Jackson also support YAML support.

Pre-Requisite



        <dependencies>
        <!-- Jackson JSON Processor -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.4.1</version>
        </dependency>
        <!-- For YAML -->
        <dependency>
            <groupId>org.yaml</groupId>
            <artifactId>snakeyaml</artifactId>
            <version>1.21</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.dataformat</groupId>
            <artifactId>jackson-dataformat-yaml</artifactId>
            <version>2.1.2</version>
        </dependency>
    </dependencies>   

Sample YAML Documents File


---
# My personal record
name: Saurabh Kumar Gupta
Title: Sr. Project Lead
skill: JAVA/J2EE
employed: True
domains:
    - Telecom
    - Finance
    - Banking
    - Healthcare
languages:
    ELK: Medium
    JAVA: Expertize
    Scripting: Comfortable
education: |
    MCA
    B.Sc
    Diploma

---
# Gaurav personal record
name: Gaurav Gupta
Title: Project Lead
skill: ELK
employed: True
domains:
    - Telecom
    - Banking
    - Healthcare
languages:
    ELK: Medium
    JAVA: Expertize
    Scripting: Comfortable
    Bigdata: Expertize
education: |
    MCA
    B.Sc

Code to Convert YAML documents to JSON Objects

package com.fiot.examples.yaml;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Iterator;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.SafeConstructor;

public class ConvertYAMLObjectsToJSON {
	public static void main(String[] args) {
		try (InputStream input = new FileInputStream(new File(
				"F:\\Workspace-Blog\\TestExamples\\src\\main\\resources\\YAMLDocument2.yaml"))) {
			Yaml yaml = new Yaml(new SafeConstructor());
			Iterator iterator = yaml.loadAll(input).iterator();
			while (iterator.hasNext()) {
				System.out.println(iterator.next());
			}
		} catch (Throwable e) {
			System.out.println("ERROR: " + e.getMessage());
		}
	}
}

Output


{name=Saurabh Kumar Gupta, Title=Sr. Project Lead, skill=JAVA/J2EE, employed=true, domains=[Telecom, Finance, Banking, Healthcare], languages={ELK=Medium, JAVA=Expertize, Scripting=Comfortable}, education=MCA
B.Sc
Diploma
}
{name=Gaurav Gupta, Title=Project Lead, skill=ELK, employed=true, domains=[Telecom, Banking, Healthcare], languages={ELK=Medium, JAVA=Expertize, Scripting=Comfortable, Bigdata=Expertize}, education=MCA
B.Sc}

More

To know more about YAML Syntax, Configuration with Java and other supporting language, frameworks and tools, Sample configuration files and JSON and YAML conversion follow below YAML Tutorials and YAML related exceptions follow YAML Issues.

JAVA : How to convert YAML To JSON?

Here is code to convert YAML document to JSON by Jackson and snakeyml apis. Jackson also support YAML support.

Pre-Requisite


<dependencies>
        <!-- Jackson JSON Processor -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.4.1</version>
        </dependency>
        <!-- For YAML -->
        <dependency>
            <groupId>org.yaml</groupId>
            <artifactId>snakeyaml</artifactId>
            <version>1.21</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.dataformat</groupId>
            <artifactId>jackson-dataformat-yaml</artifactId>
            <version>2.1.2</version>
        </dependency>
    </dependencies>

Sample YAML File


---
# My personal record
name: Saurabh Kumar Gupta
Title: Sr. Project Lead
skill: JAVA/J2EE
employed: True
domains:
    - Telecom
    - Finance
    - Banking
    - Healthcare
languages:
    ELK: Medium
    JAVA: Expertize
    Scripting: Comfortable
education: |
    MCA
    B.Sc
    Diploma
...

Code to convert YAML to JSON data

package com.fiot.examples.yaml;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;

public class ConvertYAMLToJSON {
	public static void main(String[] args) {
		String content = "";
		try {
			content = new String(Files.readAllBytes(Paths.get(
					"F:\\Workspace-Blog\\TestExamples\\src\\main\\resources\\YAMLDocument.yaml")));
			System.out.println("*********Content from YAML File ****************");
			System.out.println(content);
			String json = convertYamlToJson(content);
			System.out.println("*********Cnverted JSON from YAML File ****************");
			System.out.println(json);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private static String convertYamlToJson(String yaml) {
		try {
			ObjectMapper yamlReader = new ObjectMapper(new YAMLFactory());
			Object obj = yamlReader.readValue(yaml, Object.class);
			ObjectMapper jsonWriter = new ObjectMapper();
			return jsonWriter.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
		} catch (JsonProcessingException ex) {
			ex.printStackTrace();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
		return null;
	}
}

Output


*********Content from YAML File ****************
---
# My personal record
name: Saurabh Kumar Gupta
Title: Sr. Project Lead
skill: JAVA/J2EE
employed: True
domains:
    - Telecom
    - Finance
    - Banking
    - Healthcare
languages:
    ELK: Medium
    JAVA: Expertize
    Scripting: Comfortable
education: |
    MCA
    B.Sc
    Diploma
...
*********Cnverted JSON from YAML File ****************
{
  "name" : "Saurabh Kumar Gupta",
  "Title" : "Sr. Project Lead",
  "skill" : "JAVA/J2EE",
  "employed" : true,
  "domains" : [ "Telecom", "Finance", "Banking", "Healthcare" ],
  "languages" : {
    "ELK" : "Medium",
    "JAVA" : "Expertize",
    "Scripting" : "Comfortable"
  },
  "education" : "MCA\nB.Sc\nDiploma\n"
}

Below are some online tools to convert YAML/YML to JSON.
https://codebeautify.org/yaml-to-json-xml-csv
http://convertjson.com/yaml-to-json.htm

More

To know more about YAML Syntax, Configuration with Java and other supporting language, frameworks and tools, Sample configuration files and JSON and YAML conversion follow below YAML Tutorials and YAML related exceptions follow YAML Issues.

Difference between YAML and JSON

 

“YAML is superset of JSON”

Below are comparison between YAML and JSON by conceptually and writing differences

YAML vs JSON

  • YAML is best suited for configuration while JSON is better as a serialization format or serving up data for your APIs.
  • YAML is by no means  a replacement for JSON .You should use the data format that makes the most sense for what you are trying to accomplish.

YAML Advantage

  • YAML has a couple of big advantages  including the ability to self reference, support for complex datatypes, embedded block literals, comments, and more.
  • Write your configuration files in YAML format where you have the opportunity – it is designed to be readable and easily editable by humans.

JSON Disadvantage

  • JSON designed to be human readable – intentionally lacking features to support editing.
  • JSON doesn’t support comments – this is intentionally left out of the JSON specification because its not what the format was designed for.

JSON vs YAML

  • JSON is well suited for  serialization format to data interchange between apis over network.
  • JSON ships with a far simpler specification than YAML.
  • JSON  learning is faster in comparison to YAML, because it is not nearly as robust in its feature set.
  • YAML is a superset of JSON, which means you can parse JSON with a YAML parser.

JSON Advantage

  • JSON is  best to data interchange.

Disadvantage of YAML

  • YAML parsers are younger and  known to be less secure.
  • YAML is mainly designed for configuration when use for data interchange , many of YAMLs features lose their appeal.

Syntax Difference between YAML and JSON

Below are some syntax difference in YAML and JSON while writing files:

JSON Syntax

  • JSON is a subset of the JavaScript object notation syntax.
  • JSON data stored in name/value pairs.
  • JSON records separated by commas.
  • JSON field names & strings are wrapped by double quotes.

YAML Syntax

  • YAML stands for ain’t markup language and is a superset of JSON – You Convert YAML to JSON
  • YAML files begin with ‘—‘, marking the start of the document.
  • YAML documents end with ‘…’ but it’s optional.
  • YAML key value pairs are separated by colon.
  • YAML lists begin with a hyphen.

More

To know more about YAML Syntax, Configuration with Java and other supporting language, frameworks and tools, Sample configuration files and JSON and YAML conversion follow below YAML Tutorials and YAML related exceptions follow YAML Issues.

 

YAML Introduction

YAML(Ain’t Markup Language) is a human friendly , cross language, unicode based data serialization format designed for interaction with all programming languages.

File Name Extension : .yml or .yaml

Latest Release : 1.2

It is broadly use for programming:

  • Configuration Files
  • Internet Messaging
  • Object Persistence to data auditing
  • Also support for Unicode standards characters.

YAML allow data to show itself in a natural and meaningful way and provide a unique cleanness by minimizing the amount of structural characters.
For example: indentation may be used for structure, colons use to separate “mapping key: value” pairs, and dashes are used to create “bullet” lists for showing collections of data.

YAML is a superset of JSON : you can convert YAML to JSON by different API’s

YAML Goals

Below are main design goals for YAML :

  • YAML is easily readable and understandable by humans.
  • YAML is expressive and extensible.
  • YAML is easy to implement and use.
  • YAML matches the native data structures of agile languages.
  • YAML data is portable between programming languages.
  • YAML has a consistent model to support generic tools.
  • YAML supports one-pass processing.

YAML Documents Processing

A YAML document is parsed only when the iterator is invoked (lazy evaluation).

More

To know more about YAML Syntax, Configuration with Java and other supporting language, frameworks and tools, Sample configuration files and JSON and YAML conversion follow below YAML Tutorials and YAML related exceptions follow YAML Issues.

 

How to validate YAML/YML?

You can follow YAML syntax and semantics to create YAML files as explained in previous post.

YAML Syntax

Below are some online tools to validate YAML/YML file . you just need to copy and paste there.

http://www.yamllint.com/

https://codebeautify.org/yaml-validator

http://beautifytools.com/yaml-validator.php

https://jsonformatter.org/yaml-validator

More

To know more about YAML Syntax, Configuration with Java and other supporting language, frameworks and tools, Sample configuration files and JSON and YAML conversion follow below YAML Tutorials and YAML related exceptions follow YAML Issues.

 

YAML Syntax

By using below example of YAML file content will explain about YAML syntax so that easily understandable.

Example :

---
# My personal record
name: Saurabh Kumar Gupta
Title: Sr. Project Lead
skill: JAVA/J2EE
employed: True
domains:
    - Telecom
    - Finance
    - Banking
    - Healthcare
languages:
    ELK: Medium
    JAVA: Expertize
    Scripting: Comfortable
education: |
    MCA
    B.Sc
    Diploma
...

Comments  

YAML documents comments start with #.

Example  : #My personal record

Documents

YAML documents start with (- – -)  and ends with (. . .) (optional)

Example : as above YAML content having only one document.

List

YAML all members of a list are lines beginning at the same indentation level starting with a “-” (a dash and a space).

Example: as above YAML content having domains list as below

domains:
    - Telecom
    - Finance
    - Banking
    - Healthcare

Dictionary

A YAML dictionary is represented in a simple key: value form (the colon must be followed by a space).

Example : as above YAML content having dictionary as languages.

languages:
    ELK: Medium
    JAVA: Expertize
    Scripting: Comfortable

List and Dictionary Together

---
# Employee records
- Saurabh
   name: Saurabh Kumar Gupta
   Title: Sr. Project Lead
   skill: JAVA/J2EE
   employed: True
   domains:
     - Telecom
     - Finance
     - Banking
     - Healthcare
- Gaurav
   name: Gaurav Kumar Gupta
   Title: Project Lead
   skill: ELK
   employed: True
   domains:
     - Telecom
     - Finance
     

Boolean

you can also specify a boolean value (true/false) in several forms.

employed: yes
employed: no
employed: True
employed: false
employed: TRUE

If need to use Boolean value as String Literal use as below

employed: "yes"
employed: "no"
employed: "True"
employed: "false"
employed: "TRUE"

Multiline Value

YAML values can span multiple lines using two ways by  | or >.

  •  “Literal Block Scalar” | will include the newlines and any trailing spaces.
  • Folded Block Scalar” > will fold newlines to spaces;

It’s used to make what would otherwise be a very long line easier to read and edit. In either case the indentation will be ignored.

education: |
    MCA
    B.Sc
    Diploma

and

education: '>
     MCA
     B.Sc
     Diploma'

Special Characters

YAML allowed anything to put unquoted but there are some special cases where need to show value with quote.

Character (:) represents as mapping and Character (#) for comments. if these characters are occurs with space in any text value will use with (‘ ‘ or ” “) quotes.

Example :

description: 'you can write your code here: so that we can copy.'
or
description: "you can write your code here: so that we can copy."

The difference between single quotes and double quotes is that in double quotes you can use escapes.

description: "it\'s time to go home."

Variables

YAML uses “{{ var }}” for variables. If a any value after a colon starts with a “{” (curly bracket), YAML will think it is a dictionary, so you must quote it, like so:

Example :

log_file :"{{ LOG_DIR}}\\apps\\app_logs-*.log"

Note:

These reserved or special characters (‘ ” :[] {} > | * & ! % # ` @ ,) can not be used as first character of unquoted scalar. Only allowed characters are ( ? :  ) on beginning of string if a non-space character follows. Better always use quote for these type of scalar values.

YAML Supporting Language, Framework and Tools

YAML Supports so many languages and frameworks below are YAML Supporting languages, frameworks and respective tools :

C/C++ Libraries:

  • libyaml
  • libcyaml
  • Syck
  • yaml-cpp

Crystal:

  • YAML

Ruby:

  • psych
  • RbYaml
  • yaml4r

Python:

  • PyYAML
  • ruamel.yaml
  • PySyck

Java:

  •  JvYaml
  • SnakeYAML
  • YamlBeans
  • JYaml
  • Camel

Perl Modules:

  • YAML
  • YAML::XS
  • YAML::Syck
  • YAML::Tiny
  • PlYaml

C#/.NET:

  • YamlDotNet
  • yaml-net
  • yatools.net

Golang:

  •  Go-yaml
  • Go-gypsy

PHP:

  • php-yaml
  • syck
  • spyc

OCaml:

  • ocaml-syck

Javascript:

  • JS-YAML
  • JS-YAML Online

Actionscript:

  • as3yaml

Haskell:

  • YamlReference

Dart:

  • yaml

Rust:

  • yaml-rust
  • serde-yaml

Nim:

  • NimYAML

Others:

  • yamlvim (src)

Related Projects:

  • Rx
  • Kwalify
  • yaml_vim
  • yatools.net
  • JSON
  • Pygments

References

http://yaml.org/

More

To know more about YAML Syntax, Configuration with Java and other supporting language, frameworks and tools, Sample configuration files and JSON and YAML conversion follow below YAML Tutorials and YAML related exceptions follow YAML Issues.

 

How to Enable YAML Editor in Eclipse?

Below are steps to Enable YAML/YML editor on eclipse IDE.

  • Open Eclipse IDE
  • Go to Help menu -> Eclipse Marketplace.
  • Search for term “YAML”
  • You will get lots of option select “YAML Editor” and click on install as in below screen.
YAML Editor in Eclipse
Enable YAML/YML Editor on Eclipse
  • Click check box corresponding to “Accept Terms and Conditions”.
  • Click on Apply button and restart eclipse.

More

To know more about YAML Syntax, Configuration with Java and other supporting language, frameworks and tools, Sample configuration files and JSON and YAML conversion follow below YAML Tutorials and YAML related exceptions follow YAML Issues.