Below are some curated jq tips:
- Get key names from JSON using jq jq 'keys' file.json
- Prettify a JSON file cat input-file.json | jq > output-file.json
- Count array elements within a string echo '[{"name": "Sonia"}, {"name": "Dave"}]' | jq '. | length'
- Count array elements within a file jq '. | length' input-file.json If the JSON records contain the same number of elements, you can simply print the first output line as follows: jq '. | length' input-file.json | head -1
- Count elements in nested arrays echo '{"users":[{"name": "Sonia"}, {"name": "Dave"}]}' | jq '.users | length'
- Get values within an array of objects Assuming you have an array of objects defined as follows:
{
"teis": [
{
"created": "2022-07-28T13:36:27.981",
"modifiedBy": "admin",
"name": "Jasmine",
"value": "[-11.4569446816544,8.08529544735806]",
"psi": {
"id": "aa93b509271"
},
"de": {
"id": "F3ogKBuviRA"
}
},
{
"created": "2022-07-28T13:36:27.981",
"modifiedBy": "admin",
"name": "Jordan",
"value": "54",
"psi": {
"id": "aa93b509271"
},
"de": {
"id": "qrur9Dvnyt5"
}
}
]
}
To get all the id s of the psi property:
cat input-file.json | jq '.teis[].psi.id'
jq '.teis[].psi.id' input-file.json
To get the result as an array, rather than a list of strings: jq -s 'map(.teis[].psi.id)' input-file.json To get only unique values returned in the array: jq -s 'map(.teis[].psi.id) | unique' input-file.json Count the number of unique items returned: jq -s 'map(.teis[].psi.id) | unique | length' input-file.json Concatenate extracted values as CSV: cat input-file.json | jq -r '.teis[].psi.id' | paste -sd "," > output.csv