简体   繁体   English

Postgres 将多行放入单个 json object

[英]Postgres get multiple rows into a single json object

I have a users table with columns like id , name , email , etc. I want to retrieve information of some users in the following format in a single json object:我有一个用户表,其中包含idnameemail等列。我想在单个 json object 中以以下格式检索一些用户的信息:

{
    "userId_1" : {"name" : "A", "email": "A@gmail.com"},
    "userId_2" : {"name" : "B", "email": "B@gmail.com"}
}

Wherein the users unique id is the key and a json containing his information is its corresponding value.其中用户的唯一id是key,一个包含他信息的json是其对应的值。

I am able to get this information in two separate rows using json_build_object but I would want it get it in a single row in the form of one single json object.我可以使用json_build_object在两个单独的行中获取此信息,但我希望它以单个 json object 的形式在单个行中获取。

You can use json aggregation functions:您可以使用 json 聚合函数:

select jsonb_object_agg(id, to_jsonb(t) - 'id') res
from mytable t

jsonb_object_agg() aggregates key/value pairs into a single object. jsonb_object_agg()将键/值对聚合到单个 object 中。 The key is the id of each row, and the values is a jsonb object made of all columns of the table except id .键是每一行的id ,值是一个 jsonb object,由表中除id之外的所有列组成。

Demo on DB Fiddle DB Fiddle 上的演示

Sample data:样本数据:

id       | name | email      
:------- | :--- | :----------
userid_1 | A    | A@gmail.com
userid_2 | B    | B@gmail.com

Results:结果:

| res                                                                                                    |
| :----------------------------------------------------------------------------------------------------- |
| {"userid_1": {"name": "A", "email": "A@gmail.com"}, "userid_2": {"name": "B", "email": "B@gmail.com"}} |

try -尝试 -

select row_to_json(col) from T

link below might help https://hashrocket.com/blog/posts/faster-json-generation-with-postgresql下面的链接可能会帮助https://hashrocket.com/blog/posts/faster-json-generation-with-postgresql

Try this:尝试这个:

SELECT json_object(array_agg(id), array_agg(json::text)) FROM ( SELECT id, json_build_object('name', name, 'email', email) as json FROM users_table ) some_alias_name SELECT json_object(array_agg(id), array_agg(json::text)) FROM ( SELECT id, json_build_object('name', name, 'email', email) as json FROM users_table ) some_alias_name

If your id is not of text type then you have to cast it to text too.如果您的 id 不是文本类型,那么您也必须将其转换为文本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM