Encode operators will take the piped in object structure and encode it as a string in the desired format. The decode operators do the opposite, they take a formatted string and decode it into the relevant object structure.
Note that you can optionally pass an indent value to the encode functions (see below).
These operators are useful to process yaml documents that have stringified embedded yaml/json/props in them.
Format
Decode (from string)
Encode (to string)
Yaml
from_yaml
to_yaml(i)/@yaml
JSON
from_json
to_json(i)/@json
Properties
from_props
to_props/@props
CSV
​
to_csv/@csv
TSV
​
to_tsv/@tsv
XML
from_xml
to_xml(i)/@xml
Base64
@base64d
@base64
CSV and TSV format both accept either a single array or scalars (representing a single row), or an array of array of scalars (representing multiple rows).
XML uses the --xml-attribute-prefix and xml-content-name flags to identify attributes and content fields.
Base64 assumes rfc4648 encoding. Encoding and decoding both assume that the content is a string.
Note that versions prior to 4.18 require the 'eval/e' command to be specified.
yq e <exp> <file>
Encode value as json string
Given a sample.yml file of:
1
a:
2
cool: thing
Copied!
then
1
yq '.b = (.a | to_json)' sample.yml
Copied!
will output
1
a:
2
cool: thing
3
b:|
4
{
5
"cool": "thing"
6
}
Copied!
Encode value as json string, on one line
Pass in a 0 indent to print json on a single line.
Given a sample.yml file of:
1
a:
2
cool: thing
Copied!
then
1
yq '.b = (.a | to_json(0))' sample.yml
Copied!
will output
1
a:
2
cool: thing
3
b:'{"cool":"thing"}'
Copied!
Encode value as json string, on one line shorthand
Pass in a 0 indent to print json on a single line.
Given a sample.yml file of:
1
a:
2
cool: thing
Copied!
then
1
yq '.b = (.a | @json)' sample.yml
Copied!
will output
1
a:
2
cool: thing
3
b:'{"cool":"thing"}'
Copied!
Decode a json encoded string
Keep in mind JSON is a subset of YAML. If you want idiomatic yaml, pipe through the style operator to clear out the JSON styling.
Given a sample.yml file of:
1
a:'{"cool":"thing"}'
Copied!
then
1
yq '.a | from_json | ... style=""' sample.yml
Copied!
will output
1
cool: thing
Copied!
Encode value as props string
Given a sample.yml file of:
1
a:
2
cool: thing
Copied!
then
1
yq '.b = (.a | @props)' sample.yml
Copied!
will output
1
a:
2
cool: thing
3
b:|
4
cool = thing
Copied!
Decode props encoded string
Given a sample.yml file of:
1
a:|-
2
cats=great
3
dogs=cool as well
Copied!
then
1
yq '.a |= from_props' sample.yml
Copied!
will output
1
a:
2
cats: great
3
dogs: cool as well
Copied!
Encode value as yaml string
Indent defaults to 2
Given a sample.yml file of:
1
a:
2
cool:
3
bob: dylan
Copied!
then
1
yq '.b = (.a | to_yaml)' sample.yml
Copied!
will output
1
a:
2
cool:
3
bob: dylan
4
b:|
5
cool:
6
bob: dylan
Copied!
Encode value as yaml string, with custom indentation
You can specify the indentation level as the first parameter.