如何将文本完全转换为jsonb for postgresql列

Ish*_*war 4 postgresql json jsonb postgresql-9.4

我所拥有的是Postgresql中的一个文本列,我想将其转换为JSONB列.

我试过的是这个:

  1. CREATE TABLE test (id serial, sec text, name text);
  2. INSERT INTO test (id, sec, name) VALUES (1,'{"gender":"male","sections":{"a":1,"b":2}}','subject');
  3. ALTER TABLE test ALTER COLUMN sec TYPE JSONB USING sec::JSONB;

这确实将文本列转换为jsonb.

但是,如果我尝试查询:

 SELECT sec->>'sections'->>'a' FROM test
Run Code Online (Sandbox Code Playgroud)

我收到一个错误.

我看到转换仅在一个级别完成(即: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;
Run Code Online (Sandbox Code Playgroud)

kli*_*lin 6

操作员->>给出文本作为结果.->如果您需要使用jsonb:

select 
    pg_typeof(sec->>'sections') a,
    pg_typeof(sec->'sections') b
from test;

  a   |   b   
------+-------
 text | jsonb
(1 row) 
Run Code Online (Sandbox Code Playgroud)

使用:

select sec->'sections'->>'a' 
from test;
Run Code Online (Sandbox Code Playgroud)