Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I count specific JSON items in Bash, or another shell?

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.

like image 773
Rawan-25 Avatar asked Sep 05 '25 11:09

Rawan-25


1 Answers

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
like image 185
Ruslan Osmanov Avatar answered Sep 08 '25 12:09

Ruslan Osmanov