jq: Quick Start and Command Example

This post shows examples of jq usage.


what is jq?

jq is a command-line JSON parser.

It can pretty print JSON, access specified keys & values, etc.


install

% brew install jq

% jq --version

jq-1.6

sample.json

Assume that you have un-formatted json as a API-call result.
[{"name":"n1","created":"2021-02-15","settings":[{"name":"setting1","value":"value1"},{"name":"setting2","value":"value2"}]},{"name":"n2","created":"2021-02-16","settings":[{"name":"setting1","value":"value1"}]}]

examples

pretty format

% cat sample.json | jq .

[

  {

    "name": "n1",

    "created": "2021-02-15",

    "settings": [

      {

        "name": "setting1",

        "value": "value1"

      },

      {

        "name": "setting2",

        "value": "value2"

      }

    ]

  },

  {

    "name": "n2",

    "created": "2021-02-16",

    "settings": [

      {

        "name": "setting1",

        "value": "value1"

      }

    ]

  }

]

remove array bracket

% cat sample.json | jq -r '.[]'

{

  "name": "n1",

  "created": "2021-02-15",

  "settings": [

    {

      "name": "setting1",

      "value": "value1"

    },

    {

      "name": "setting2",

      "value": "value2"

    }

  ]

}

{

  "name": "n2",

  "created": "2021-02-16",

  "settings": [

    {

      "name": "setting1",

      "value": "value1"

    }

  ]

}

select first element of array

% cat sample.json | jq -r '.[0]'

{

  "name": "n1",

  "created": "2021-02-15",

  "settings": [

    {

      "name": "setting1",

      "value": "value1"

    },

    {

      "name": "setting2",

      "value": "value2"

    }

  ]

}

list names

% cat sample.json | jq -r '.[].name'

n1

n2

list names (as array format)

% cat sample.json | jq -r '.[] | [.name]'

[

  "n1"

]

[

  "n2"

]

list settings.name

% cat sample.json | jq -r '.[].settings[].name'

setting1

setting2

setting1

list names & settings.name

% cat sample.json | jq -r '.[] | {name: .name, setting_name: .settings[].name}'

{

  "name": "n1",

  "setting_name": "setting1"

}

{

  "name": "n1",

  "setting_name": "setting2"

}

{

  "name": "n2",

  "setting_name": "setting1"

}

objects into arrays

% cat sample.json | jq -r '.[] | {name: .name, setting_name: .settings[].name} | [.name, .setting_name]'

[

  "n1",

  "setting1"

]

[

  "n1",

  "setting2"

]

[

  "n2",

  "setting1"

]

arrays to csv

% cat sample.json | jq -r '.[] | {name: .name, setting_name: .settings[].name} | [.name, .setting_name] | @csv'

"n1","setting1"

"n1","setting2"

"n2","setting1"


Comments

Popular posts from this blog

Minikube Installation for M1 Mac

Selenide: Quick Start

Ansistrano (Ansible + Capistrano): Quick Start