如何将 postgresql 列的文本完全转换为 jsonb
How to convert text to jsonb entirely for a postgresql column
我有一个 Postgresql 中的文本列,我想将其转换为 JSONB 列。
我试过的是这样的:
CREATE TABLE test (id serial, sec text, name text);
INSERT INTO test (id, sec, name) VALUES (1,'{"gender":"male","sections":{"a":1,"b":2}}','subject');
ALTER TABLE test ALTER COLUMN sec TYPE JSONB USING sec::JSONB;
这确实将文本列转换为 jsonb
。
但是,如果我尝试查询:
SELECT sec->>'sections'->>'a' FROM test
我收到一个错误。
我看到转换仅在一个级别完成(即:sec->>'sections' 工作正常)。
查询 SELECT pg_typeof(name->>'sections') from test;
给我的列类型为文本。
有什么方法可以将文本完全转换为 jsonb,以便我可以成功查询 SELECT sec->>'sections'->>'a' FROM test;
?
我不想在如下查询中将文本转换为 json,因为稍后我需要在 'a' 上创建索引。
select (sec->>'sections')::json->>'a' from test;
运算符->>
给出一个文本作为结果。如果需要 jsonb
:
,请使用 ->
select
pg_typeof(sec->>'sections') a,
pg_typeof(sec->'sections') b
from test;
a | b
------+-------
text | jsonb
(1 row)
使用:
select sec->'sections'->>'a'
from test;
或者更好的是,使用 operator #>>
:
SELECT sec #>> '{sections,a}' FROM test;
要在表达式索引中使用它,您需要额外的括号:
CREATE INDEX foo ON test ((sec #>> '{sections,a}'));
确保在查询中使用匹配表达式(不带括号)以允许使用索引。
我有一个 Postgresql 中的文本列,我想将其转换为 JSONB 列。
我试过的是这样的:
CREATE TABLE test (id serial, sec text, name text);
INSERT INTO test (id, sec, name) VALUES (1,'{"gender":"male","sections":{"a":1,"b":2}}','subject');
ALTER TABLE test ALTER COLUMN sec TYPE JSONB USING sec::JSONB;
这确实将文本列转换为 jsonb
。
但是,如果我尝试查询:
SELECT sec->>'sections'->>'a' FROM test
我收到一个错误。
我看到转换仅在一个级别完成(即:sec->>'sections' 工作正常)。
查询 SELECT pg_typeof(name->>'sections') from test;
给我的列类型为文本。
有什么方法可以将文本完全转换为 jsonb,以便我可以成功查询 SELECT sec->>'sections'->>'a' FROM test;
?
我不想在如下查询中将文本转换为 json,因为稍后我需要在 'a' 上创建索引。
select (sec->>'sections')::json->>'a' from test;
运算符->>
给出一个文本作为结果。如果需要 jsonb
:
->
select
pg_typeof(sec->>'sections') a,
pg_typeof(sec->'sections') b
from test;
a | b
------+-------
text | jsonb
(1 row)
使用:
select sec->'sections'->>'a'
from test;
或者更好的是,使用 operator #>>
:
SELECT sec #>> '{sections,a}' FROM test;
要在表达式索引中使用它,您需要额外的括号:
CREATE INDEX foo ON test ((sec #>> '{sections,a}'));
确保在查询中使用匹配表达式(不带括号)以允许使用索引。