gpt4 book ai didi

json - 如何将 postgresql 列的文本完全转换为 jsonb

转载 作者:行者123 更新时间:2023-11-29 11:31:36 25 4
gpt4 key购买 nike

我有一个 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}}', '主题');
  3. ALTER TABLE 测试 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;

关于json - 如何将 postgresql 列的文本完全转换为 jsonb,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38436178/

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