Convert JSON file to YAML using JQ
Article shows you how to convert a json file into yaml by using 'jq' utility.
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.
- Official YAML Spec
- Official JSON Spec
- JQ Tool (jq is like ‘sed’ for JSON data)
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
Today’s Quote
All the wealth acquired with perseverance (hard-work) by the worthy is for the exercise of benevolence (kindness).
- Kural 212 - Thiru Valluvar ( His Work )