如何使pgsql返回json数组

时间:2018-12-26 06:22:09

标签: json postgresql jsonb

每个人,我都面临将数据转换为json对象的问题。有一个称为里程碑的表,其中包含以下数据:

id  name    parentId
a   test1   A
b   test2   B
c   test3   C

我想将结果转换为Postgres中的json类型:

[{"id": "a", "name": "test1", "parentId": "A"}]
[{"id": "b", "name": "test2", "parentId": "B"}]
[{"id": "c", "name": "test3", "parentId": "C"}]

如果有人知道如何处理,请告诉我,谢谢

2 个答案:

答案 0 :(得分:1)

您可以使用to_jsonb()将表的每一行作为简单的json对象:

select to_jsonb(m)
from milestone m

                   to_jsonb                    
-----------------------------------------------
 {"id": "a", "name": "test1", "parentid": "A"}
 {"id": "b", "name": "test2", "parentid": "B"}
 {"id": "c", "name": "test3", "parentid": "C"}
(3 rows)

如果要为每行获取一个元素数组,请使用jsonb_build_array()

select jsonb_build_array(to_jsonb(m))
from milestone m

                jsonb_build_array                
-------------------------------------------------
 [{"id": "a", "name": "test1", "parentid": "A"}]
 [{"id": "b", "name": "test2", "parentid": "B"}]
 [{"id": "c", "name": "test3", "parentid": "C"}]
(3 rows)

您还可以使用jsonb_agg()将所有行作为json数组获取:

select jsonb_agg(to_jsonb(m))
from milestone m

                                                                   jsonb_agg                                                                   
-----------------------------------------------------------------------------------------------------------------------------------------------
 [{"id": "a", "name": "test1", "parentid": "A"}, {"id": "b", "name": "test2", "parentid": "B"}, {"id": "c", "name": "test3", "parentid": "C"}]
(1 row)

阅读文档中的JSON Functions and Operators

答案 1 :(得分:0)

您可以使用ROW_TO_JSON

来自文档

  

将行作为JSON对象返回。将在之间添加换行符   如果pretty_bool为true,则为level-1元素。

对于查询:

select 
  row_to_json(tbl) 
from 
 (select * from tbl) as tbl;

您可以在DEMO

中查看