Working with JSON

Encode and decode to and from JSON. Supports multiple JSON documents in a single file (e.g. NDJSON).

Note that YAML is a superset of (single document) JSON - so you don't have to use the JSON parser to read JSON when there is only one JSON document in the input. You will probably want to pretty print the result in this case, to get idiomatic YAML styling.

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:

{"cat": "meow"}

then

yq -p=json sample.json

will output

cat: meow

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:

{"a":"Easy! as one two three","b":{"c":2,"d":[3,4]}}

then

yq -p=json sample.json

will output

Encode json: simple

Given a sample.yml file of:

then

will output

Encode json: simple - in one line

Given a sample.yml file of:

then

will output

Encode json: comments

Given a sample.yml file of:

then

will output

Encode json: anchors

Anchors are dereferenced

Given a sample.yml file of:

then

will output

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:

then

will output

Roundtrip JSON Lines / NDJSON

Given a sample.json file of:

then

will output

Roundtrip multi-document JSON

The parser can also handle multiple multi-line json documents in a single file (despite this not being in the JSON Lines / NDJSON spec). Typically you would have one entire JSON document per line, but the parser also supports multiple multi-line json documents

Given a sample.json file of:

then

will output

Update a specific document in a multi-document json

Documents are indexed by the documentIndex or di operator.

Given a sample.json file of:

then

will output

Find and update a specific document in a multi-document json

Use expressions as you normally would.

Given a sample.json file of:

then

will output

Decode JSON Lines / NDJSON

Given a sample.json file of:

then

will output

Last updated

Was this helpful?