多行到json

Sta*_*nko 7 postgresql select json

看起来我的问题很不寻常,因为我根本没有找到答案。让我们想象一下,我有一个A带有列的表:languageuri

语言 | uri             
----------|-----------------
茹 | 一些uri        
zh | 另一个uri
...

我的问题是:如何返回 JSON 对象而不是多行。例如:

{ "ru": "some-uri", "en": "some-another-uri", ... }

Sta*_*nko 9

所以,我在很远的文档中找到了答案。

SELECT json_object(array_agg(language), array_agg(uri)) FROM A 会给你预期的结果。

  • 您需要将字段(如语言和 uri)转换为 ::text,以防它们不是文本 (2认同)

Dmi*_*sev 5

还有另一种不需要类型转换的方法:json_object_agg(name, value)

test=# create table t (name text, value int);
CREATE TABLE
test=# insert into t values ('key1', 1), ('key2', 2), ('key3', 3);
INSERT 0 3
test=# select * from t;
 name | value
------+-------
 key1 |     1
 key2 |     2
 key3 |     3
(3 rows)

test=# select json_object_agg(name, value) from t;
            json_object_agg
----------------------------------------
 { "key1" : 1, "key2" : 2, "key3" : 3 }
(1 row)
Run Code Online (Sandbox Code Playgroud)