JSON defines only two data structures: objects and arrays. An object is a set of name-value pairs, and an array is a list of values. JSON defines seven value types: string, number, object, array, true, false, and null.
Similar to other programming languages, a JSON Array is a list of items surrounded in square brackets ([]). Each item in the array is separated by a comma.
Just throwing another solution in the mix...
Try jq, a lightweight and flexible command-line JSON processor:
jq length /tmp/test.json
Prints the length of the array of objects.
The shortest expression is
curl 'http://…' | jq length
You can also use jq to track down the array within the returned json and then pipe that in to a second jq call to get its length. Suppose it was in a property called records, like {"records":[...]}.
$ curl https://my-source-of-json.com/list | jq -r '.records | length'
2
$
A simple solution is to install jshon library :
jshon -l < /tmp/test.json
2
If the JSON is being read from a file, try this -
number_of_objects=`jq '. | length' json_file_name.json`
echo $number_of_objects
If the JSON array is inside a key in the JSON as shown below -
{
"fruits": [
"apples",
"oranges",
"pears"
]
}
try this -
number_of_objects=`jq '.fruits | length' json_file_name.json`
echo $number_of_objects
(You'll have to download jq for this solution to work)
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