JQ

From Bonus Bits
Jump to: navigation, search

Description

This article gives references to useful syntax related to jq (Json Query) command.

Example Json

For no particular reason; we'll use this Chef Workstation version manifest parsed down as our example json file.

/opt/chef-workstation/version-manifest.json

{
  "manifest_format": 2,
  "software": {
    "go": {
      "locked_version": "1.13.1",
      "locked_source": {
        "sha256": "f3985fced3adecb62dd1e636cfa5eb9fea8f3e98101d9fcc4964d8f1ec255b7f",
        "url": "https://dl.google.com/go/go1.13.1.darwin-amd64.tar.gz"
      },
      "source_type": "url",
      "described_version": "1.13.1",
      "license": "BSD-3-Clause"
    },
    "ruby": {
      "locked_version": "2.7.2",
      "locked_source": {
        "sha256": "6e5706d0d4ee4e1e2f883db9d768586b4d06567debea353c796ec45e8321c3d4",
        "url": "https://cache.ruby-lang.org/pub/ruby/2.7/ruby-2.7.2.tar.gz"
      },
      "source_type": "url",
      "described_version": "2.7.2",
      "license": "BSD-2-Clause"
    },
    "rust": {
      "locked_version": "1.37.0",
      "locked_source": {
        "sha256": "b2310c97ffb964f253c4088c8d29865f876a49da2a45305493af5b5c7a3ca73d",
        "url": "https://static.rust-lang.org/dist/rust-1.37.0-x86_64-apple-darwin.tar.gz"
      },
      "source_type": "url",
      "described_version": "1.37.0",
      "license": "Apache-2.0"
    }
  },
  "build_version": "21.3.332",
  "build_git_revision": "30137a2d9c60642f6f16f42abb2b7d8b496cfd6d",
  "license": "Chef EULA"
}


Pretty Print File Contents

cat /opt/chef-workstation/version-manifest.json | jq .


Single Value at Root

cat /opt/chef-workstation/version-manifest.json | jq '.build_version'

Output

"21.3.332"


Single Nested Value

cat /opt/chef-workstation/version-manifest.json | jq '.software.ruby.described_version'

Output

"2.7.2"


Full Nested Section

cat /opt/chef-workstation/version-manifest.json | jq '.software.ruby'

Output

{
  "locked_version": "2.7.2",
  "locked_source": {
    "sha256": "6e5706d0d4ee4e1e2f883db9d768586b4d06567debea353c796ec45e8321c3d4",
    "url": "https://cache.ruby-lang.org/pub/ruby/2.7/ruby-2.7.2.tar.gz"
  },
  "source_type": "url",
  "described_version": "2.7.2",
  "license": "BSD-2-Clause"
}


Sources