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/@yamld
to_yaml(i)/@yaml
JSON
from_json/@jsond
to_json(i)/@json
Properties
from_props/@propsd
to_props/@props
CSV
from_csv/@csvd
to_csv/@csv
TSV
from_tsv/@tsvd
to_tsv/@tsv
XML
from_xml/@xmld
to_xml(i)/@xml
Base64
@base64d
@base64
URI
@urid
@uri
Shell
@sh
See CSV and TSV for accepted formats.
XML uses the --xml-attribute-prefix and xml-content-name flags to identify attributes and content fields.
Base64 assumes encoding. Encoding and decoding both assume that the content is a utf-8 string and not binary content.
Encode value as json string
Given a sample.yml file of:
a:
cool: thing
then
yq '.b = (.a | to_json)' sample.yml
will output
a:
cool: thing
b: |
{
"cool": "thing"
}
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:
a:
cool: thing
then
yq '.b = (.a | to_json(0))' sample.yml
will output
a:
cool: thing
b: '{"cool":"thing"}'
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:
a:
cool: thing
then
yq '.b = (.a | @json)' sample.yml
will output
a:
cool: thing
b: '{"cool":"thing"}'
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:
a: '{"cool":"thing"}'
then
yq '.a | from_json | ... style=""' sample.yml
will output
cool: thing
Encode value as props string
Given a sample.yml file of:
a:
cool: thing
then
yq '.b = (.a | @props)' sample.yml
will output
a:
cool: thing
b: |
cool = thing
Decode props encoded string
Given a sample.yml file of:
a: |-
cats=great
dogs=cool as well
then
yq '.a |= @propsd' sample.yml
will output
a:
cats: great
dogs: cool as well
Decode csv encoded string
Given a sample.yml file of:
a: |-
cats,dogs
great,cool as well
then
yq '.a |= @csvd' sample.yml
will output
a:
- cats: great
dogs: cool as well
Decode tsv encoded string
Given a sample.yml file of:
a: |-
cats dogs
great cool as well
then
yq '.a |= @tsvd' sample.yml
will output
a:
- cats: great
dogs: cool as well
Encode value as yaml string
Indent defaults to 2
Given a sample.yml file of:
a:
cool:
bob: dylan
then
yq '.b = (.a | to_yaml)' sample.yml
will output
a:
cool:
bob: dylan
b: |
cool:
bob: dylan
Encode value as yaml string, with custom indentation
You can specify the indentation level as the first parameter.