I have JSON data in the following form:
{
"home": [{
"pageid": "about yft",
"pageData": "0908782"
},
{
"pageData": "09897"
}]}
How do I get the total number of home->pageid
items?
Here is what I have tried so far:
$curFileName ={{Path_of_json_file.json}}
appName0=$(cat $curFileName | jq -c '.["home"][]["pageid"]' | sed 's/"//g');
${#appName0[@]} # to get the length of pageid but didn't success..
But it didn't return the desired results.
Collect the pageid
items of "string"
type into an array, then return the length of the array:
n=$(jq '[.home[].pageid | select(type == "string")] | length' < file.json)
Alternatively, check if the items in the home
array have pageid
. If the item has the property, put 1
into the result array, otherwise put zero. Finally sum the zeroes and ones with add
function:
n=$(jq '[.home[] | if has("pageid") then 1 else 0 end] | add' < file.json)
Here is how you should print the number:
printf '%d\n' "$n"
Sample Output
3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With