vincentlcy vincentlcy - 1 year ago 124
JSON Question

How to count setof / number of keys of JSON in postgresql?

I have a column in

storing a map, like
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

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


setof text Returns set of keys in the outermost JSON object.
json_object_keys('{"f1":"abc","f2":{"f3":"a", "f4":"b"}}')


Crosstab isn't feasible as the number of key could be large.

Answer Source

You could convert keys to array and use array_length to get this:

select array_length(array_agg(A.key), 1) from (
    select json_object_keys('{"f1":"abc","f2":{"f3":"a", "f4":"b"}}') as key
) A;

If you need to get this for the whole table, you can just group by primary key.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download