y
y
yq
Search…
Working with JSON

Yaml to Json

To convert output to json, use the --output-format=json (or -o=j) flag. You can change the json output format by using the indent flag.
Given a sample.yaml file of:
1
b:
2
c: 2
Copied!
then
1
yq eval -o=j sample.yaml
Copied!
will output
1
{
2
"b": {
3
"c": 2
4
}
5
}
Copied!
To format the json:
1
yq eval -o=j -I=0 sample.yaml
Copied!
will yield
1
{"b":{"c":2}}
Copied!

Multiple matches

Each matching yaml node will be converted to json and printed out as a separate json doc. You may want to set the indent flags to 0 if you want a json doc per line.
Given a sample.yaml file of:
1
bob:
2
c: 2
3
bab:
4
c: 5
Copied!
then
1
yq eval -o=j '.b*' sample.yaml
Copied!
will output
1
{
2
"c": 2
3
}
4
{
5
"c": 5
6
}
Copied!

Json to Yaml

To read in json, just pass in a json file instead of yaml, it will just work - as json is a subset of yaml. However, you will probably want to use the Style Operator or --prettyPrint/-P flag to make look more like an idiomatic yaml document. This can be done by resetting the style of all elements.
e.g given a json file
1
{"a":"Easy! as one two three","b":{"c":2,"d":[3,4]}}
Copied!
then
1
yq eval -P sample.json
Copied!
will output
1
a: Easy! as one two three
2
b:
3
c: 2
4
d:
5
- 3
6
- 4
Copied!
Last modified 1mo ago