简体   繁体   中英

Postgresql: How to get a json where one column is the key and another column is the value?

I have a table as follows. The repliesto is a unique and not null column and devicetokens is an array:

CREATE TABLE devices(
                     repliesto    TEXT PRIMARY KEY CHECK (repliesto <> ''), 
                     devicetokens TEXT[] NOT NULL 
                       CHECK (ARRAY_LENGTH(devicetokens, 1) IS NOT NULL 
                          AND ARRAY_LENGTH(devicetokens, 1) > 0)
);

Sample data:

SELECT * FROM devices ;
repliesto devicetokens
user1 {a}
user2 {b,c}

I need to get a single json where repliesto column is the key and the devicetokens array is the value as follows:

{"user1": ["a"], "user2": ["b","c"]}

I am able to use this:

SELECT jsonb_agg(json_build_object(repliesto, devicetokens)) FROM devices;

But this gives me the following:

[{"user1": ["a"]}, {"user2": ["b", "c"]}]

This is different from what I want as it's an array of each individual row as a json. I want a single json (not array) where the repliesto column is the key and the devicetokens array is the value. How can I do that?

In PostgreSQL v9.5+ there is an aggregate function json_object_agg(name, value)

SELECT 
  json_object_agg(repliesto, array_to_json(devicetokens))
FROM 
  devices;

Result:

{ "user1" : ["a"], "user2" : ["b","c"] }

You are welcome to try it out in db<>fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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