y
y
yq
Search…
Working with JSON
Encode and decode to and from JSON. Note that YAML is a superset of JSON - so yq can read any json file without doing anything special.
This means you don't need to 'convert' a JSON file to YAML - however if you want idiomatic YAML styling, then you can use the -P/--prettyPrint flag, see examples below.

Parse json: simple

JSON is a subset of yaml, so all you need to do is prettify the output
Given a sample.json file of:
1
{"cat": "meow"}
Copied!
then
1
yq e -P '.' sample.json
Copied!
will output
1
cat: meow
Copied!

Parse json: complex

JSON is a subset of yaml, so all you need to do is prettify the output
Given a sample.json file of:
1
{"a":"Easy! as one two three","b":{"c":2,"d":[3,4]}}
Copied!
then
1
yq e -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!

Encode json: simple

Given a sample.yml file of:
1
cat: meow
Copied!
then
1
yq e -o=json '.' sample.yml
Copied!
will output
1
{
2
"cat": "meow"
3
}
Copied!

Encode json: simple - in one line

Given a sample.yml file of:
1
cat: meow # this is a comment, and it will be dropped.
Copied!
then
1
yq e -o=json -I=0 '.' sample.yml
Copied!
will output
1
{"cat":"meow"}
Copied!

Encode json: comments

Given a sample.yml file of:
1
cat: meow # this is a comment, and it will be dropped.
Copied!
then
1
yq e -o=json '.' sample.yml
Copied!
will output
1
{
2
"cat": "meow"
3
}
Copied!

Encode json: anchors

Anchors are dereferenced
Given a sample.yml file of:
1
cat: &ref meow
2
anotherCat: *ref
Copied!
then
1
yq e -o=json '.' sample.yml
Copied!
will output
1
{
2
"cat": "meow",
3
"anotherCat": "meow"
4
}
Copied!

Encode json: multiple results

Each matching node is converted into a json doc. This is best used with 0 indent (json document per line)
Given a sample.yml file of:
1
things: [{stuff: cool}, {whatever: cat}]
Copied!
then
1
yq e -o=json -I=0 '.things[]' sample.yml
Copied!
will output
1
{"stuff":"cool"}
2
{"whatever":"cat"}
Copied!
Last modified 3d ago