DevOps

Convert JSON file to YAML using JQ

What is this article about?

When you are working on the web or with DevOps or GitOps, you will have cases where you want to transform a JSON file to YAML. This article walks you though converting the JSON document to YAML using the “jq” tool.

Why YAML (over JSON)?

Here are a few reasons why developers prefer YAML over JSON:

  • YAML is visually easier to look at. (Sometimes the {…} syntax with JSON can overwhelm your eyes with too much noise.)
  • YAML has support for comments (JSON does not have a way to add comments.) YAML comments begin with the number sign (#)
  • YAML has supports multiline strings using the “block style indicator” (|). It further enhances it with “block chomping indicator” with the use of (+), (-), default.
    • The block style indicates how newlines inside the block should behave.
    • The chomping indicator controls what should happen with newlines at the end of the string.
    • See YAML Multiline for a very good description on the usage.

Prerequisite

  • Make sure you have downloaded JQ and placed it in your PATH.
  • Edit and place the following into ~/.jq
def yamlify2:
    (objects | to_entries | (map(.key | length) | max + 2) as $w |
        .[] | (.value | type) as $type |
        if $type == "array" then
            "\(.key):", (.value | yamlify2)
        elif $type == "object" then
            "\(.key):", "    \(.value | yamlify2)"
        else
            "\(.key):\(" " * (.key | $w - length))\(.value)"
        end
    )
    // (arrays | select(length > 0)[] | [yamlify2] |
        "  - \(.[0])", "    \(.[1:][])"
    )
    // .
    ;

The above code adds a new function “yamlify2” to your library of jq functions.

JSON to YAML conversion using JQ

Now we are ready to convert a JSON document to YAML.

Syntax:

jq -r yamlify2 input.json
# or
jq -r yamlify2 input.json > output.yaml

Working Example:

Filename: glossary.json

{
    "glossary": {
        "title": "example glossary",
		"GlossDiv": {
            "title": "S",
			"GlossList": {
                "GlossEntry": {
                    "ID": "SGML",
					"SortAs": "SGML",
					"GlossTerm": "Standard Generalized Markup Language",
					"Acronym": "SGML",
					"Abbrev": "ISO 8879:1986",
					"GlossDef": {
                        "para": "A meta-markup language, used to create markup languages such as DocBook.",
						"GlossSeeAlso": ["GML", "XML"]
                    },
					"GlossSee": "markup"
                }
            }
        }
    }
}
jq -r yamlify2 glossary.json
# or
jq -r yamlify2 glossary.json > glossary.yaml

Result (under glossary.yaml)

glossary:
    title:     example glossary
    GlossDiv:
        title:      S
        GlossList:
            GlossEntry:
                ID:         SGML
                SortAs:     SGML
                GlossTerm:  Standard Generalized Markup Language
                Acronym:    SGML
                Abbrev:     ISO 8879:1986
                GlossDef:
                    para:          A meta-markup language, used to create markup languages such as DocBook.
                    GlossSeeAlso:
                      - GML
                      - XML
                GlossSee:   markup

You should have a YAML file ready to use in your project.

Cheers

Published on Java Code Geeks with permission by Venkatt Guhesan, partner at our JCG program. See the original article here: Convert JSON file to YAML using JQ

Opinions expressed by Java Code Geeks contributors are their own.

Venkatt Guhesan

I work as an Enterprise UI Architect for DataDirect Networks. I have been developing DirectMon, an Enterprise Monitoring and Management Solution for all of the DDN products. Before that I worked at DrFirst engineering an e-prescribing platform for controlled substances
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Logan Palanisamy
Logan Palanisamy
1 year ago

Very good. Thank you so much

Back to top button