yq: Command-line YAML/XML/TOML processor - jq wrapper for YAML, XML, TOML documents#

Installation#

pip install yq

Before using yq, you also have to install its dependency, jq. See the jq installation instructions for details and directions specific to your platform.

On macOS, yq is also available on Homebrew: use brew install python-yq.

Synopsis#

yq takes YAML input, converts it to JSON, and pipes it to jq:

cat input.yml | yq .foo.bar

Like in jq, you can also specify input filename(s) as arguments:

yq .foo.bar input.yml

By default, no conversion of jq output is done. Use the --yaml-output/-y option to convert it back into YAML:

cat input.yml | yq -y .foo.bar

Mapping key order is preserved. By default, custom YAML tags and styles in the input are ignored. Use the --yaml-roundtrip/-Y option to preserve YAML tags and styles by representing them as extra items in their enclosing mappings and sequences while in JSON:

yq -Y .foo.bar input.yml

yq can be called as a module if needed. With -y/-Y, files can be edited in place like with sed -i:

python -m yq -Y --indentless --in-place '.["current-context"] = "staging-cluster"' ~/.kube/config

Use the --width/-w option to pass the line wrap width for string literals. Use --explicit-start/--explicit-end to emit YAML start/end markers even when processing a single document. All other command line arguments are forwarded to jq. yq forwards the exit code jq produced, unless there was an error in YAML parsing, in which case the exit code is 1. See the jq manual for more details on jq features and options.

Because YAML treats JSON as a dialect of YAML, you can use yq to convert JSON to YAML: yq -y . < in.json > out.yml.

Preserving tags and styles using the -Y (--yaml-roundtrip) option#

The -Y option helps preserve custom string styles and tags in your document. For example, consider the following document (an AWS CloudFormation template fragment):

Resources:
  ElasticLoadBalancer:
    Type: 'AWS::ElasticLoadBalancing::LoadBalancer'
    Properties:
      AvailabilityZones: !GetAZs ''
      Instances:
        - !Ref Ec2Instance1
        - !Ref Ec2Instance2
      Description: >-
        Load balancer for Big Important Service.

        Good thing it's managed by this template.

Passing this document through yq -y .Resources.ElasticLoadBalancer will drop custom tags, such as !Ref, and styles, such as the folded style of the Description field:

Type: AWS::ElasticLoadBalancing::LoadBalancer
Properties:
  AvailabilityZones: ''
  Instances:
    - Ec2Instance1
    - Ec2Instance2
  Description: 'Load balancer for Big Important Service.

    Good thing it''s managed by this template.'

By contrast, passing it through yq -Y .Resources.ElasticLoadBalancer will preserve tags and styles:

Type: 'AWS::ElasticLoadBalancing::LoadBalancer'
Properties:
  AvailabilityZones: !GetAZs ''
  Instances:
    - !Ref 'Ec2Instance1'
    - !Ref 'Ec2Instance2'
  Description: >-
    Load balancer for Big Important Service.

    Good thing it's managed by this template.

To accomplish this in -Y mode, yq carries extra metadata (mapping pairs and sequence values) in the JSON representation of your document for any custom tags or styles that it finds. When converting the JSON back into YAML, it parses this metadata, re-applies the tags and styles, and discards the extra pairs and values.

Warning

The -Y option is incompatible with jq filters that do not expect the extra information injected into the document to preserve the YAML formatting. For example, a jq filter that counts entries in the Instances array will come up with 4 entries instead of 2. A filter that expects all array entries to be mappings may break due to the presence of string metadata keys. Check your jq filter for compatibility/semantic validity when using the -Y option.

yq does not support passing YAML comments into the JSON representation used by jq, or roundtripping such comments.

XML support#

yq also supports XML. The yq package installs an executable, xq, which transcodes XML to JSON using xmltodict and pipes it to jq. Roundtrip transcoding is available with the xq --xml-output/xq -x option. Multiple XML documents can be passed in separate files/streams as xq a.xml b.xml. Use --xml-item-depth to descend into large documents, streaming their contents without loading the full doc into memory (for example, stream a Wikipedia database dump with cat enwiki-*.xml.bz2 | bunzip2 | xq . --xml-item-depth=2). Entity expansion and DTD resolution is disabled to avoid XML parsing vulnerabilities. Use python -m yq.xq if you want to ensure a specific Python runtime.

TOML support#

yq supports TOML as well. The yq package installs an executable, tomlq, which uses the tomlkit library to transcode TOML to JSON, then pipes it to jq. Roundtrip transcoding is available with the tomlq --toml-output/tomlq -t option. Use python -m yq.tomlq if you want to ensure a specific Python runtime.

Compatibility note

This package’s release series available on PyPI begins with version 2.0.0. Versions of yq prior to 2.0.0 are distributed by https://github.com/abesto/yq and are not related to this package. No guarantees of compatibility are made between abesto/yq and kislyuk/yq. This package follows the Semantic Versioning 2.0.0 standard. To ensure proper operation, declare dependency version ranges according to SemVer.

Authors#

  • Andrey Kislyuk

License#

Licensed under the terms of the Apache License, Version 2.0.

https://github.com/kislyuk/yq/workflows/Python%20package/badge.svg https://codecov.io/github/kislyuk/yq/coverage.svg?branch=master https://img.shields.io/pypi/v/yq.svg https://img.shields.io/pypi/l/yq.svg

CLI usage#

yq#

usage: yq [options] <jq filter> [input file...]
          [--indentless-lists] [--explicit-start] [--explicit-end]
          [--in-place] [--version]
          [jq_filter] [files ...]

yq: Command-line YAML processor - jq wrapper for YAML documents

yq transcodes YAML documents to JSON and passes them to jq.
See https://github.com/kislyuk/yq for more information.

positional arguments:
  jq_filter
  files

options:
  -h, --help            show this help message and exit
  --yaml-output, --yml-output, -y
                        Transcode jq JSON output back into YAML and emit it
  --yaml-roundtrip, --yml-roundtrip, -Y
                        Transcode jq JSON output back into YAML and emit it. Preserve YAML tags and styles by representing them as extra items in their enclosing mappings and sequences while in JSON. This option is incompatible with jq filters that do not expect these extra items.
  --yaml-output-grammar-version {1.1,1.2}, --yml-out-ver {1.1,1.2}
                        When using --yaml-output, specify output grammar (the default is 1.1 and will be changed to 1.2 in a future version). Setting this to 1.2 will cause strings like 'on' and 'no' to be emitted unquoted.
  --width WIDTH, -w WIDTH
                        When using --yaml-output, specify string wrap width
  --indentless-lists, --indentless
                        When using --yaml-output, indent block style lists (sequences) with 0 spaces instead of 2
  --explicit-start      When using --yaml-output, always emit explicit document start ("---")
  --explicit-end        When using --yaml-output, always emit explicit document end ("...")
  --in-place, -i        Edit files in place (no backup - use caution)
  --version             show program's version number and exit

jq - commandline JSON processor [version 1.7]

Usage:	jq [options] <jq filter> [file...]
	jq [options] --args <jq filter> [strings...]
	jq [options] --jsonargs <jq filter> [JSON_TEXTS...]

jq is a tool for processing JSON inputs, applying the given filter to
its JSON text inputs and producing the filter's results as JSON on
standard output.

The simplest filter is ., which copies jq's input to its output
unmodified except for formatting. For more advanced filters see
the jq(1) manpage ("man jq") and/or https://jqlang.github.io/jq/.

Example:

	$ echo '{"foo": 0}' | jq .
	{
	  "foo": 0
	}

Command options:
  -n, --null-input          use `null` as the single input value;
  -R, --raw-input           read each line as string instead of JSON;
  -s, --slurp               read all inputs into an array and use it as
                            the single input value;
  -c, --compact-output      compact instead of pretty-printed output;
  -r, --raw-output          output strings without escapes and quotes;
      --raw-output0         implies -r and output NUL after each output;
  -j, --join-output         implies -r and output without newline after
                            each output;
  -a, --ascii-output        output strings by only ASCII characters
                            using escape sequences;
  -S, --sort-keys           sort keys of each object on output;
  -C, --color-output        colorize JSON output;
  -M, --monochrome-output   disable colored output;
      --tab                 use tabs for indentation;
      --indent n            use n spaces for indentation (max 7 spaces);
      --unbuffered          flush output stream after each output;
      --stream              parse the input value in streaming fashion;
      --stream-errors       implies --stream and report parse error as
                            an array;
      --seq                 parse input/output as application/json-seq;
  -f, --from-file file      load filter from the file;
  -L directory              search modules from the directory;
      --arg name value      set $name to the string value;
      --argjson name value  set $name to the JSON value;
      --slurpfile name file set $name to an array of JSON values read
                            from the file;
      --rawfile name file   set $name to string contents of file;
      --args                consume remaining arguments as positional
                            string values;
      --jsonargs            consume remaining arguments as positional
                            JSON values;
  -e, --exit-status         set exit status code based on the output;
  -V, --version             show the version;
  --build-configuration     show jq's build configuration;
  -h, --help                show the help;
  --                        terminates argument processing;

Named arguments are also available as $ARGS.named[], while
positional arguments are available as $ARGS.positional[].

xq#

usage: xq [options] <jq filter> [input file...]
          [--version]
          [jq_filter] [files ...]

xq: Command-line XML processor - jq wrapper for XML documents

xq transcodes XML documents to JSON and passes them to jq.
See https://github.com/kislyuk/xq for more information.

positional arguments:
  jq_filter
  files

options:
  -h, --help            show this help message and exit
  --xml-output, -x      Transcode jq JSON output back into XML and emit it
  --xml-item-depth 123  Specify depth of items to emit (default 0; use a positive integer to stream large docs)
  --xml-dtd             Preserve XML Document Type Definition (disables streaming of multiple docs)
  --xml-root XML_ROOT   When transcoding back to XML, envelope the output in an element with this name
  --xml-force-list ELT  Emit a list for elements with this name even if they occur only once (option can repeat)
  --in-place, -i        Edit files in place (no backup - use caution)
  --version             show program's version number and exit

jq - commandline JSON processor [version 1.7]

Usage:	jq [options] <jq filter> [file...]
	jq [options] --args <jq filter> [strings...]
	jq [options] --jsonargs <jq filter> [JSON_TEXTS...]

jq is a tool for processing JSON inputs, applying the given filter to
its JSON text inputs and producing the filter's results as JSON on
standard output.

The simplest filter is ., which copies jq's input to its output
unmodified except for formatting. For more advanced filters see
the jq(1) manpage ("man jq") and/or https://jqlang.github.io/jq/.

Example:

	$ echo '{"foo": 0}' | jq .
	{
	  "foo": 0
	}

Command options:
  -n, --null-input          use `null` as the single input value;
  -R, --raw-input           read each line as string instead of JSON;
  -s, --slurp               read all inputs into an array and use it as
                            the single input value;
  -c, --compact-output      compact instead of pretty-printed output;
  -r, --raw-output          output strings without escapes and quotes;
      --raw-output0         implies -r and output NUL after each output;
  -j, --join-output         implies -r and output without newline after
                            each output;
  -a, --ascii-output        output strings by only ASCII characters
                            using escape sequences;
  -S, --sort-keys           sort keys of each object on output;
  -C, --color-output        colorize JSON output;
  -M, --monochrome-output   disable colored output;
      --tab                 use tabs for indentation;
      --indent n            use n spaces for indentation (max 7 spaces);
      --unbuffered          flush output stream after each output;
      --stream              parse the input value in streaming fashion;
      --stream-errors       implies --stream and report parse error as
                            an array;
      --seq                 parse input/output as application/json-seq;
  -f, --from-file file      load filter from the file;
  -L directory              search modules from the directory;
      --arg name value      set $name to the string value;
      --argjson name value  set $name to the JSON value;
      --slurpfile name file set $name to an array of JSON values read
                            from the file;
      --rawfile name file   set $name to string contents of file;
      --args                consume remaining arguments as positional
                            string values;
      --jsonargs            consume remaining arguments as positional
                            JSON values;
  -e, --exit-status         set exit status code based on the output;
  -V, --version             show the version;
  --build-configuration     show jq's build configuration;
  -h, --help                show the help;
  --                        terminates argument processing;

Named arguments are also available as $ARGS.named[], while
positional arguments are available as $ARGS.positional[].

tomlq#

usage: tomlq [options] <jq filter> [input file...]

tomlq: Command-line TOML processor - jq wrapper for TOML documents

tomlq transcodes TOML documents to JSON and passes them to jq.
See https://github.com/kislyuk/tomlq for more information.

positional arguments:
  jq_filter
  files

options:
  -h, --help         show this help message and exit
  --toml-output, -t  Transcode jq JSON output back into TOML and emit it
  --in-place, -i     Edit files in place (no backup - use caution)
  --version          show program's version number and exit

jq - commandline JSON processor [version 1.7]

Usage:	jq [options] <jq filter> [file...]
	jq [options] --args <jq filter> [strings...]
	jq [options] --jsonargs <jq filter> [JSON_TEXTS...]

jq is a tool for processing JSON inputs, applying the given filter to
its JSON text inputs and producing the filter's results as JSON on
standard output.

The simplest filter is ., which copies jq's input to its output
unmodified except for formatting. For more advanced filters see
the jq(1) manpage ("man jq") and/or https://jqlang.github.io/jq/.

Example:

	$ echo '{"foo": 0}' | jq .
	{
	  "foo": 0
	}

Command options:
  -n, --null-input          use `null` as the single input value;
  -R, --raw-input           read each line as string instead of JSON;
  -s, --slurp               read all inputs into an array and use it as
                            the single input value;
  -c, --compact-output      compact instead of pretty-printed output;
  -r, --raw-output          output strings without escapes and quotes;
      --raw-output0         implies -r and output NUL after each output;
  -j, --join-output         implies -r and output without newline after
                            each output;
  -a, --ascii-output        output strings by only ASCII characters
                            using escape sequences;
  -S, --sort-keys           sort keys of each object on output;
  -C, --color-output        colorize JSON output;
  -M, --monochrome-output   disable colored output;
      --tab                 use tabs for indentation;
      --indent n            use n spaces for indentation (max 7 spaces);
      --unbuffered          flush output stream after each output;
      --stream              parse the input value in streaming fashion;
      --stream-errors       implies --stream and report parse error as
                            an array;
      --seq                 parse input/output as application/json-seq;
  -f, --from-file file      load filter from the file;
  -L directory              search modules from the directory;
      --arg name value      set $name to the string value;
      --argjson name value  set $name to the JSON value;
      --slurpfile name file set $name to an array of JSON values read
                            from the file;
      --rawfile name file   set $name to string contents of file;
      --args                consume remaining arguments as positional
                            string values;
      --jsonargs            consume remaining arguments as positional
                            JSON values;
  -e, --exit-status         set exit status code based on the output;
  -V, --version             show the version;
  --build-configuration     show jq's build configuration;
  -h, --help                show the help;
  --                        terminates argument processing;

Named arguments are also available as $ARGS.named[], while
positional arguments are available as $ARGS.positional[].

Change log#