jq is pure awesomeness. If every you want to “grep” through JSON data on the command line, this is the tool for you. Unfortunately, I don’t use it everyday, so when I do go to use it I forget the details for doing some basic operations.
Sample Data
[
{
"name": "Homer Simpson",
"occupation": "Nuclear Safety Inspector"
},
{
"name": "Marge Simpson",
"occupation": "Mayor"
},
{
"name": "Milhouse Van Houten",
"occupation": "Student"
},
{
"name": "Homeboy Van Somebody",
"occupation": "Lawyer"
}
]
Filtering
Often you will have json and you’ll want to filter out all objects that do not meet some criteria.
Selecting objects with a specific value
❯ jq '.[] | select (.name == "Homer Simpson")' sample.json
{
"name": "Homer Simpson",
"occupation": "Nuclear Safety Inspector"
}
Outputting a new JSON object based on the input data
❯ jq '.[] | select (.name == "Homer Simpson") | {character_name: .name, job: .occupation}' sample.json
{
"character_name": "Homer Simpson",
"job": "Nuclear Safety Inspector"
}
Using a regex
❯ jq '.[] | select (.name | test("Home"))' sample.json
{
"name": "Homer Simpson",
"occupation": "Nuclear Safety Inspector"
}
{
"name": "Homeboy Van Somebody",
"occupation": "Lawyer"
}