I have a column in jsonb
storing a map, like {'a':1,'b':2,'c':3}
where the number of keys is different in each row.
I want to count it -- jsonb_object_keys can retrieve the keys but it is in setof
Are there something like this?
(select count(jsonb_object_keys(obj) from XXX )
(this won't work as ERROR: set-valued function called in context that cannot accept a set
)
Postgres JSON Functions and Operators Document
json_object_keys(json)
jsonb_object_keys(jsonb)
setof text Returns set of keys in the outermost JSON object.
json_object_keys('{"f1":"abc","f2":{"f3":"a", "f4":"b"}}')
json_object_keys
------------------
f1
f2
Crosstab isn't feasible as the number of key could be large.
While a sub select must be used to convert the JSON keys set to rows, the following tweaked query might run faster by skipping building the temporary array:
and it's a bit shorter ;)
To make it a function:
Alternately, you could simply return the upper bounds of the keys when listed as an array:
Using
'{"a": 1, "b": 2, "c": 3}'::jsonb
as obj, count would result in a value of three (3).Pasteable example:
You could convert keys to array and use array_length to get this:
If you need to get this for the whole table, you can just group by primary key.
Shortest:
Returns 3
If you want all json number of keys from a table, it gives: