Skip to content

Instantly share code, notes, and snippets.

@juanje
Last active Apr 13, 2020
Embed
What would you like to do?
Filter json file with jq

Filter json file with jq

Let's say we have the file data.json with a json compacted in one line:

$ cat data.json
{"employees":[{"name":"Shyam","email":"shyamjaiswal@example.com"},{"name":"Bob","email":"bob32@example.com"},{"name":"Jai","email":"jai87@example.com"}]}

We can use the command jq to see it in with nicer format:

$ cat data.json | jq .
{
  "employees": [
    {
      "name": "Shyam",
      "email": "shyamjaiswal@example.com"
    },
    {
      "name": "Bob",
      "email": "bob32@example.com"
    },
    {
      "name": "Jai",
      "email": "jai87@example.com"
    }
  ]
}

You can also see just the elements of the employeeslist (array):

$ cat data.json | jq '.employees[]'
{
  "name": "Shyam",
  "email": "shyamjaiswal@example.com"
}
{
  "name": "Bob",
  "email": "bob32@example.com"
}
{
  "name": "Jai",
  "email": "jai87@example.com"
}

But, also filter and show some data from the json file:

$ cat data.json | jq '.employees[] | { name }'
{
  "name": "Shyam"
}
{
  "name": "Bob"
}
{
  "name": "Jai"
}

NOTE: The [] after .employees is to tell jq that you are going to ask or do something with the list/array named employees.

You can also ask for specific value:

$ cat /tmp/data.json | jq '.employees[] | select(.name|test("Bob")) | { email }'
{
  "email": "bob32@example.com"
}

To explain a bit this:

.employees[] | will takes the list of employees and pass to the next command.

select(.name|test("Bob")) will iterate all the elements of the list and check the value of the key name and select just the ones that coincides with the test() function. In this case, the word Bob.

{ email } will add to the result dictionary the values for the key email from the results of the previous step, for each one of the results.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment