y
y
yq
Search…
Encode / Decode
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 embeded yaml/json/props in them.

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 eval '.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.
Given a sample.yml file of:
1
a:
2
cool:
3
bob: dylan
Copied!
then
1
yq eval '.b = (.a | to_yaml(8))' 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, using toyaml

Does the same thing as to_yaml, matching jq naming convention.
Given a sample.yml file of:
1
a:
2
cool: thing
Copied!
then
1
yq eval '.b = (.a | to_yaml)' sample.yml
Copied!
will output
1
a:
2
cool: thing
3
b: |
4
cool: thing
Copied!

Encode value as json string

Given a sample.yml file of:
1
a:
2
cool: thing
Copied!
then
1
yq eval '.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 eval '.b = (.a | to_json(0))' sample.yml
Copied!
will output
1
a:
2
cool: thing
3
b: '{"cool":"thing"}'
Copied!

Encode value as props string

Given a sample.yml file of:
1
a:
2
cool: thing
Copied!
then
1
yq eval '.b = (.a | to_props)' sample.yml
Copied!
will output
1
a:
2
cool: thing
3
b: |
4
cool = thing
Copied!

Decode a yaml encoded string

Given a sample.yml file of:
1
a: 'foo: bar'
Copied!
then
1
yq eval '.b = (.a | from_yaml)' sample.yml
Copied!
will output
1
a: 'foo: bar'
2
b:
3
foo: bar
Copied!

Update a multiline encoded yaml string

Given a sample.yml file of:
1
a: |
2
foo: bar
3
baz: dog
Copied!
then
1
yq eval '.a |= (from_yaml | .foo = "cat" | to_yaml)' sample.yml
Copied!
will output
1
a: |
2
foo: cat
3
baz: dog
Copied!

Update a single line encoded yaml string

Given a sample.yml file of:
1
a: 'foo: bar'
Copied!
then
1
yq eval '.a |= (from_yaml | .foo = "cat" | to_yaml)' sample.yml
Copied!
will output
1
a: 'foo: cat'
Copied!
Last modified 29d ago