gpt4 book ai didi

sql - 将 postgres 字符串列转换为 json

转载 作者:行者123 更新时间:2023-11-29 12:41:17 24 4
gpt4 key购买 nike

我有一个用户表,我想在其中使用 {"oldfield": < 当前行中 foo 的值 >} 将字符串列 foo 转换为 json,但我似乎找不到正确的语法。我直接使用 psql 命令行界面。

这是我尝试过的:

 ALTER TABLE user_schema.user ALTER COLUMN "foo" SET DATA TYPE json USING '{"oldfield": "foo"}';

这会将字段更改为准确的 {"oldfield":"foo"},而不是 foo 列的实际值。我还尝试了以下组合,但都因语法错误而失败。有任何想法吗?谢谢

   ALTER TABLE user_schema.user ALTER COLUMN "foo" SET DATA TYPE json USING '{"oldfield": foo}';
ERROR: invalid input syntax for type json
DETAIL: Token "foo" is invalid.
CONTEXT: JSON data, line 1: {"oldfield": foo...

ALTER TABLE user_schema.user ALTER COLUMN "foo" SET DATA TYPE json USING '{"oldfield": \"foo\"}';
ERROR: invalid input syntax for type json
DETAIL: Token "\" is invalid.
CONTEXT: JSON data, line 1: {"oldfield": \...
ALTER TABLE user_schema.user ALTER COLUMN "foo" SET DATA TYPE json USING '{"oldfield": 'foo'}';
ERROR: syntax error at or near "foo"
LINE 1: ...Metadata" SET DATA TYPE json USING '{"oldfield": 'foo...
^
ALTER TABLE user_schema.user ALTER COLUMN "foo" SET DATA TYPE json USING '{"oldfield": `foo`}';
ERROR: invalid input syntax for type json
DETAIL: Token "`" is invalid.
CONTEXT: JSON data, line 1: {"oldfield": `...
ALTER TABLE user_schema.user ALTER COLUMN "foo" SET DATA TYPE json USING '{"oldfield": user.foo}';
ERROR: invalid input syntax for type json
DETAIL: Token "user" is invalid.
CONTEXT: JSON data, line 1: {"oldfield": user...
ALTER TABLE user_schema.user ALTER COLUMN "foo" SET DATA TYPE json USING '{"oldfield": user_schema.user.foo}';
ERROR: invalid input syntax for type json
DETAIL: Token "user_schema" is invalid.
CONTEXT: JSON data, line 1: {"oldfield": user_schema...
ALTER TABLE user_schema.user ALTER COLUMN "foo" SET DATA TYPE json USING '{"oldfield": foo}';
ERROR: invalid input syntax for type json
DETAIL: Token "foo" is invalid.

最佳答案

使用函数 json_build_object():

create table my_table(foo text);
insert into my_table values
('first'),
('second');

alter table my_table
alter column foo set data type json
using json_build_object('oldfield', foo);

select *
from my_table;

foo
-------------------------
{"oldfield" : "first"}
{"oldfield" : "second"}
(2 rows)

关于sql - 将 postgres 字符串列转换为 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48818704/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com