Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect if a jsonb attribute is array or object

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
like image 411
Manquer Avatar asked Oct 29 '17 06:10

Manquer


People also ask

Can Jsonb be an 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.

How do you check if a JSON object is an array?

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.

How do I query Jsonb data in PostgreSQL?

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.


1 Answers

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' ;
like image 159
Manquer Avatar answered Sep 28 '22 03:09

Manquer