Many jsonb/json functions expect all values of the column either to be of type json array ( like jsonb_array_length
) or only an json object (like jsonb_build_oject
) .
There are some jsonb columns in the database which contain a mix of both arrays and object roots, is there any easy way to filter out arrays and objects so that queries like
SELECT DISTINCT jsonb_object_keys(my_column) FROM my_table;
cannot call jsonb_object_keys on an array
or
SELECT my_column FROM my_table WHERE jsonb_array_length(column) > 0;
cannot get array length of a non-array
jsonb[] is not an "extra" datatype, it's simply an array of JSONB values. Similar to text[] or integer[] . You can create arrays from every type.
Sometimes, you need to check a parsed JSON object or a variable to see if it's an array before iteration or before any other manipulation. You can use the Array. isArray method to check if a variable is an array.
Querying the JSON documentPostgreSQL has two native operators -> and ->> to query JSON documents. The first operator -> returns a JSON object, while the operator ->> returns text. These operators work on both JSON as well as JSONB columns. There are additional operators available for JSONB columns.
As described in documentation the functions jsonb_typeof
or json_typeof
can be used to apply this kind of filtering
like
SELECT DISTINCT jsonb_object_keys(my_column)
FROM my_table WHERE jsonb_typeof(column) ='object' ;
or
SELECT my_column FROM my_table
WHERE jsonb_array_length(column) > 0
AND jsonb_typeof(column) ='array' ;
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