Jq oneliners
Introduction
This page is to remind me of jq one liners
Sample Data
{
"id": "123",
"code": "123",
"headers": [
{
"id": "1",
"testDimension": "AB",
"testLines": [
{
"id": "1",
"test1Dimension": "1",
"test2Dimension": "2",
"test3Dimension": "3"
}
],
"shortcutCode1": "Code1",
"shortcutCode2": "Code2"
},
{
"id": "2",
"testDimension": "AB",
"testLines": [
{
"id": "1",
"test1Dimension": "1",
"test2Dimension": "2",
"test3Dimension": "3"
}
],
"shortcutCode1": "Code1",
"shortcutCode2": "Code2"
},
{
"id": "3",
"testDimension": "BC",
"testLines": [
{
"id": "1",
"test1Dimension": "1",
"test2Dimension": "2",
"test3Dimension": "3"
}
],
"shortcutCode1": "Code1",
"shortcutCode2": "Code2"
}
]
}
Show the records which are are BC
To show AB records
cat test4.json | jq '.headers[] | select(.testDimension == "AB")'
Show the records which are not BC
To remove the AB you can do this
cat test4.json | jq '.headers[] | select(.testDimension != "BC")'
Delete the records all records accept AB
To remove the AB you can do this
cat test4.json | jq 'del(.headers[] | select(.testDimension != "AB"))'
Count the AB Records
cat test4.json | jq 'del(.headers[] | select(.testDimension != "AB"))' | jq '.headers | length'
Count the Records to be deleted
For me I guess if I was to use jq to manipulate data it is handy to count stuff.
First, list the current count of all records with no -s
cat test4.json | jq '. | length'
First list them by removing the del( ... )
cat test4.json | jq '.headers[] | select(.testDimension != "AB")'
Then use can count them with the -s option
cat test4.json | jq '.headers[] | select(.testDimension != "AB")' | jq -s '. | length'