如何在postgres中将记录集转换为json数组

时间:2017-04-20 14:26:28

标签: sql postgresql

我有一张像

这样的桌子
  name | age 
   abc | 20
   pqr | 30

我希望结果像json数组一样

{
 [{
   "name":"abc",
   "age":20 
 },
 {
  "name":"pqr",
   "age":30 
 }]
}

我知道他们的方法是

row_to_json();

这将只给我一行json,但我想要数组, 请帮帮我

2 个答案:

答案 0 :(得分:3)

select json_agg(row_to_json(t))
from t
;
                      json_agg                      
----------------------------------------------------
 [{"name":"abc","age":20}, {"name":"pqr","age":30}]

答案 1 :(得分:0)

您可以尝试:

<style name="MyStyle" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>

您还可以在此链接中看到更多信息:

https://hashrocket.com/blog/posts/faster-json-generation-with-postgresql

希望它对你有用。