英文:
SQLAlchemy/PostgreSQL: Change column type from ARRAY to JSON
问题
我正在尝试将表格中的一列的数据类型从接受填充有字符串的数组更改为接受JSON的数据类型。
我尝试执行的SQL如下:
ALTER TABLE my_table
ALTER COLUMN my_column TYPE JSON USING my_column::json
但是我收到一个错误消息,错误信息为“无法将类型 character varying[] 转换为 json”。
我尝试更改的列是空的,没有任何行,因此不需要将数据转换为JSON。由于它是空的,我考虑删除该列然后重新创建,但如果可能的话,我想保留该列并只更改其数据类型。我对PostgreSQL不是很熟悉,因此对正确方向的任何指导将不胜感激。
英文:
I am trying to change the type of one of the columns on my table from one that takes arrays filled with strings to one that takes JSON.
The SQL I'm trying to execute looks like:
ALTER TABLE my_table
ALTER COLUMN my_column TYPE JSON USING my_column::json
But I get an error back saying "cannot cast type character varying[] to json".
The column I'm trying to change is empty, there are no rows so there is no data that needs to be cast to JSON. Since it's empty I've thought of dropping the column and remaking it but I'd like to keep the column and just change its type if possible. I'm not a whizz with PostgreSQL so any nudge in the right direction would be appreciated.
答案1
得分: 1
array_test
表格 "public.array_test"
列名 | 类型 | 校对 | 允许为空 | 默认值
---------------+---------------------+-----------+----------+---------
id | integer | | |
array_fld | integer[] | | |
numeric_array | numeric[] | | |
jsonb_array | jsonb[] | | |
varchar_array | character varying[] | | |
text_array | text[] | | |
ALTER TABLE array_test
ALTER COLUMN varchar_array TYPE json
USING array_to_json(varchar_array);
\d array_test
表格 "public.array_test"
列名 | 类型 | 校对 | 允许为空 | 默认值
---------------+-----------+-----------+----------+---------
id | integer | | |
array_fld | integer[] | | |
numeric_array | numeric[] | | |
jsonb_array | jsonb[] | | |
varchar_array | json | | |
text_array | text[] | | |
英文:
array_test
Table "public.array_test"
Column | Type | Collation | Nullable | Default
---------------+---------------------+-----------+----------+---------
id | integer | | |
array_fld | integer[] | | |
numeric_array | numeric[] | | |
jsonb_array | jsonb[] | | |
varchar_array | character varying[] | | |
text_array | text[] | | |
ALTER TABLE array_test
ALTER COLUMN varchar_array TYPE json
USING array_to_json(varchar_array);
\d array_test
Table "public.array_test"
Column | Type | Collation | Nullable | Default
---------------+-----------+-----------+----------+---------
id | integer | | |
array_fld | integer[] | | |
numeric_array | numeric[] | | |
jsonb_array | jsonb[] | | |
varchar_array | json | | |
text_array | text[] | | |
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论