I know that most of the users look for the jsonb
type where the retrieval of values is way faster than json
type. Still, I need the order in my key-values and so far I believe that the best way to achieve this is migrating my column type to json
.
I have tried the following:
ALTER TABLE table_name
ALTER COLUMN jsonb_colum TYPE json
and
ALTER TABLE table_name
ALTER COLUMN jsonb_colum TYPE json
USING jsonb_colum::json
In both cases I get this error:
ERROR: Operator class "jsonb_path_ops" does not accept data type json.
I have also tried to use the USING
clause with an expression as the following:
ALTER TABLE table_name
ALTER COLUMN jsonb_column TYPE json
USING jsonb_column::to_json(jsonb_colum)
But with no luck either, getting the following error:
ERROR: Type "to_json" does not exist
Is there any workaround to make my wish come true?
I’m using PostgreSQL 13.3 (Debian 13.3-1.pgdg100+1) 64-bit
3
Answers
jsonb_path_ops
is an operator class used for GIN indexes. Like:The existence of such an index would produce your first error message exactly. You need to drop any such index before you can change the column type – with your first, valid
ALTER TABLE
statement.However, the existence of such an index would indicate the need to support one or more of these
jsonb
operators:@>
,@?
,@@
. If so, consider creating an expression index after the conversion tojson
to replace the old one. Like:(Parentheses required.)
Then a query like this would still be supported (even if at slightly higher cost):
Related:
Also, be wary of the missing basic equality and inequality operators for
json
. See:A newly made json formatted column can be updated in place from the existing jsonb column using a query and selecting out the keys in the order desired. An example table, dataset,and update query is below.
The column color_json will preserve the same text as in the original data
file. The column color_jsonb will not preserve key order,
duplicate keys, additional spaces, etc.
The first 5 rows of data:
When we select the same data from the jsonb column, notice it changed the key ordering.
Name comes after rgb
We can use the function to_json() to convert the column color_jsonb back to json format, but it does not
return the original key ordering.
However we can pick out the individual keys and format them.
Alter the table to create a new column to hold the json type you want
Update the table in place with a query that selects from the jsonb
column, and formats the keys in the order you want, and uses that
to update the new color_json2 column.
Explanation of JSONB introduced by PostgreSQL
updating table rows in postgres using subquery
Please use below query for alter existing column in postgresql for text to jsonb
In above query column_name must be shown highlighted if you using pgAdmin4. Otherwise you got error when run this query.