记录到 JSONB,没有自动方式?
RECORD to JSONB, no automatic way?
jsonb_build_object('a',a, 'b',b)
是多余的(不是“自动”),而 to_jsonb(row(a,b))
是丑陋的,因为忽略了列名......没有办法做正确的事吗?
注意事项
一个典型的查询是
SELECT a,b, record_to_jsonb(c,d,e) as info FROM t
我需要一个动态解决方案,但是,为了说明,静态解决方案是定义一个数据类型,
CREATE TYPE mytest AS (c text, d int, e boolean);
SELECT a,b, to_jsonb(row(c,d,e)::mytest) as info FROM t; -- work fine!
PS:为什么 PostgreSQL 不提供 捕获列名称和值的 jsonb_to_record()
?
Either I'm not realizing to the see an elegant and eficient way to use to_jsonb
(most probable), or, maybe PostgreSQL's architect-developers forgot the concept of library function orthogonality... There is no technical problem to implement a nice record_to_jsonb()
function, as demonstrated before by functions like xmlattributes(a,b)
的逆函数。
select a, b, to_jsonb(subq) as info
from t
cross join lateral (values (c, d, e)) as subq(c, d, e);
或更短,缩写 CROSS JOIN 语法并直接使用 SELECT 子句
select a, b, to_jsonb(subq) as info
from t, lateral (select c, d, e) subq;
这样的东西可以更符合您的用例吗?我的想法是将 a
和 b
保留在 json 中,让请求代码忽略它。
select a, b, to_jsonb(t) - 'a' - 'b' as info
from t
jsonb_build_object('a',a, 'b',b)
是多余的(不是“自动”),而 to_jsonb(row(a,b))
是丑陋的,因为忽略了列名......没有办法做正确的事吗?
注意事项
一个典型的查询是
SELECT a,b, record_to_jsonb(c,d,e) as info FROM t
我需要一个动态解决方案,但是,为了说明,静态解决方案是定义一个数据类型,
CREATE TYPE mytest AS (c text, d int, e boolean);
SELECT a,b, to_jsonb(row(c,d,e)::mytest) as info FROM t; -- work fine!
PS:为什么 PostgreSQL 不提供 捕获列名称和值的 jsonb_to_record()
?
Either I'm not realizing to the see an elegant and eficient way to use to_jsonb
(most probable), or, maybe PostgreSQL's architect-developers forgot the concept of library function orthogonality... There is no technical problem to implement a nice record_to_jsonb()
function, as demonstrated before by functions like xmlattributes(a,b)
的逆函数。
select a, b, to_jsonb(subq) as info
from t
cross join lateral (values (c, d, e)) as subq(c, d, e);
或更短,缩写 CROSS JOIN 语法并直接使用 SELECT 子句
select a, b, to_jsonb(subq) as info
from t, lateral (select c, d, e) subq;
这样的东西可以更符合您的用例吗?我的想法是将 a
和 b
保留在 json 中,让请求代码忽略它。
select a, b, to_jsonb(t) - 'a' - 'b' as info
from t