Sql 如何将查询结果聚合为camelCased json格式

Sql 如何将查询结果聚合为camelCased json格式,sql,json,postgresql,Sql,Json,Postgresql,我想要一种以json格式(使用camelCase键)动态聚合任意查询结果的方法 jsonb_agg函数非常接近我想要的 --Example table create table test.foo(id int, some_col text, another_val date); insert into test.foo(id, some_col, another_val) values (1, 'Hello there', '2020-01-01'), (2, 'Bonjour',

我想要一种以json格式(使用camelCase键)动态聚合任意查询结果的方法

jsonb_agg函数非常接近我想要的

--Example table
create table test.foo(id int, some_col text, another_val date);
insert into test.foo(id, some_col, another_val)
values (1, 'Hello there', '2020-01-01'),
       (2, 'Bonjour', '1984-02-23');
--select
select jsonb_agg(f)
from test.foo f;
返回

[{"id": 1, "some_col": "Hello there", "another_val": "2020-01-01"}, {"id": 2, "some_col": "Bonjour", "another_val": "1984-02-23"}]
这几乎就是我想要的,但由于我们的应用程序需要camelCase密钥,所以我真正需要的是这个

[{"id": 1, "someCol": "Hello there", "anotherVal": "2020-01-01"}, {"id": 2, "someCol": "Bonjour", "anotherVal": "1984-02-23"}]
理想情况下,我想要一种为几乎任何select语句编写此语句的方法

select jsonb_agg_with_camel_keys(f)
from test.foo f;
-- or for functions
select jsonb_agg_with_camel_keys(f)
from test.some_function(param_one, param_two) f;
然而,据我所知,这样一个函数并不存在

目前,我们正在这样做

select array_to_json(array_agg(row_to_json(foos)))
from
    (
        select
            f.id          as id,
            f.some_col    as "someCol",
            f.another_val as "anotherVal"
        from
            test.foo f
    ) foos;
这是可行的,但由于我们经常使用这种模式,因此它很乏味,容易出错(打字错误),并且需要比一般解决方案更多的工作来维护(特别是当存在多个嵌套级别的select语句时)

理想情况下,解决方案会自动将所有键的snake_大小写转换为camelCase(包括多层嵌套json)。解决方案将是动态的(接受任何输入,就像jsonb_agg函数已经接受的那样)。该解决方案可用于表格和函数结果。 请注意,只需要更改json键。所有其他输出应保持不变。

理论上,我可以编写某种regex_替换,在聚合完成后替换json键。虽然这当然是一种可能性,但在聚合过程中进行转换似乎更有效。 我知道postgresql需要定义良好的类型,这使得编写plpgsql函数非常困难。我已经试着想了一种方法来实现这一点,但是为函数结果实现这一点是很困难的。 我也知道有一个选项是用C编写我自己的聚合函数,基本上是jsonb_agg的一个变体(如果这是最好的选项,那么请对如何这样做进行一般描述,因为我以前没有这样做过)

提前感谢您的时间和想法

编辑


对我来说,重命名列名不是一个好的解决方案。这将需要一次大的重构,而且会比它的价值要麻烦得多。

使用camel case重命名所有列,然后使用
json\u agg
,输出将使用camel case。