JSON text filtering with jq

I frequently have to intereact with some json files , since bash is the main tool i use day to day i must master the usage of jq, but i noticed that the vast majority of totorials on jq usage just sucks.
I’m going to write some kind of memo to remember the main command that i use most of the time
lets take this dummy contact.json file

{
  "contacts": [
    {
      "name": "John Smith",
      "phone": "(123) 456-7890",
      "email": "john.smith@example.com",
      "sex": "male",
      "position": "Manager",
      "birthday": "1985-06-23",
      "devices": [
        {
          "type": "laptop",
          "model": "MacBook Pro",
          "serial_number": "ABCD1234",
          "issued_date": "2022-01-15"
        },
        {
          "type": "phone",
          "model": "iPhone 12",
          "serial_number": "EFGH5678",
          "issued_date": "2022-01-15"
        }
      ]
    },
    {
      "name": "Jane Doe",
      "phone": "(234) 567-8901",
      "email": "jane.doe@example.com",
      "sex": "female",
      "position": "Sales Representative",
      "birthday": "1990-02-14",
      "devices": [
        {
          "type": "laptop",
          "model": "Dell XPS 13",
          "serial_number": "IJKL9012",
          "issued_date": "2022-03-01"
        }
      ]
    },
    {
      "name": "Bob Johnson",
      "phone": "(345) 678-9012",
      "email": "bob.johnson@example.com",
      "sex": "male",
      "position": "IT Specialist",
      "birthday": "1982-11-30",
      "devices": [
        {
          "type": "laptop",
          "model": "ThinkPad X1 Carbon",
          "serial_number": "MNOP3456",
          "issued_date": "2022-02-10"
        },
        {
          "type": "phone",
          "model": "Samsung Galaxy S21",
          "serial_number": "QRST7890",
          "issued_date": "2022-02-10"
        }
      ]
    }
  ]
}

to list the name of all the male employes in the json file
cat contact.json | jq '.contacts[] | select(.sex=="male") | .name'

this one is truly awesome , display the name of all employes that are more than 35 years old using their birthday.
cat contact.json | jq '.contacts[] | select((.birthday | strptime("%Y-%m-%d") | mktime) <= (now - 35*365*24*60*60)) | .name'

this one is going to list all the phone and their issued date
cat contact.json | jq '.contacts[].devices[] | select(.type=="phone") | {model: .model, issued_date: .issued_date}'

To display the devices issued after 2022-02-12 and their owner’s name, you can use the following jq command:
cat contact.json | jq '.contacts[] | {owner: .name, devices: [.devices[] | select(.issued_date > "2022-02-12") ] } | select(.devices != [])'

Leave a Comment

Your email address will not be published. Required fields are marked *