sebastiandaschner blog


Escape JSON property names in jq

tuesday, march 10, 2020

I’m using the command line a lot and jq is a helpful tool for dealing with JSON data. You can access JSON object properties and array elements by concatenating the property names with dots and square brackets:

$> cat ~/.docker/config.json

{
    "auths": {
        "https://index.docker.io/v1/": {
            "auth": "aBcDeFghiJKlMn="
        },
        [...]
    }
}
$> cat .docker/config.json | jq .

{
  "auths": {
    "https://index.docker.io/v1/": {
      "auth": "aBcDeFghiJKlMn="
    },
    [...]
  }
}
$> cat .docker/config.json | jq .auths
{
  "https://index.docker.io/v1/": {
    "auth": "aBcDeFghiJKlMn="
  },
  [...]
}

You can also access and escape “non-trivial” field names in different ways. You can get the encoded Docker auth authentication as follows, by using square brackets and quotes to escape the property name:

$> cat .docker/config.json | jq '.auths["https://index.docker.io/v1/"].auth'
"aBcDeFghiJKlMn="

$> cat .docker/config.json | jq -r '.auths["https://index.docker.io/v1/"].auth'
aBcDeFghiJKlMn=

You’ll notice the formatted and colorized output of jq. Have a look at the documentation.

Parts of the content of this post were reposted from my newsletter issue 038.

 

Found the post useful? Subscribe to my newsletter for more free content, tips and tricks on IT & Java:

All opinions are my own and do not reflect those of my employer or colleagues.