Amjad Omari
Amjad Omari

Reputation: 1112

get array of all json field keys in postgresql

I have a table called user, and inside the table there is a field called friends, this field is a json type has a value as in the following example

{"blockList": {"199": {"date": 1453197190, "status": 1}, "215": {"date": 1459325611, "status": 1}, "219": {"date": 1454244074, "status": 1}, "225": {"date": 1453981312, "status": 1}, "229": {"date": 1459327685, "status": 1}}, "followers": {"211": {"date": 1452503369}, "219": {"date": 1452764627}, "334": {"date": 1456396375}}, "following": {"215": {"date": 1459325619}, "219": {"date": 1453622322}, "226": {"date": 1454244887}, "229": {"date": 1459327691}}, "friendList": {"213": {"date": 1453622410, "type": 2, "status": 1}, "214": {"date": 1452763643, "status": 1}, "215": {"date": 1455606872, "type": 2, "status": 2}, "218": {"date": 1453280047, "status": 1}, "219": {"date": 1453291227, "status": 2}, "221": {"date": 1453622410, "type": 2, "status": 1}, "224": {"date": 1453380152, "type": 2, "status": 1}, "225": {"date": 1453709357, "type": 2, "status": 2}, "226": {"date": 1454244088, "type": 2, "status": 1}, "229": {"date": 1454326745, "type": 2, "status": 2}}}

this record has a blockList object that is containning objects for blocked users. what I need, is to return an array of all block list keys like this

["199", "215", "219", "225", "229"]

any help how can I write a plpgsql function to do that (return all object keys in an array)? I'm a beginner in psotgresql, and need a help please.

Upvotes: 11

Views: 13677

Answers (3)

Anton Bessonov
Anton Bessonov

Reputation: 9813

I'm late to the party, but I would like to propose following way, borrowed from Erwin here:

SELECT ARRAY(SELECT json_object_keys(friends->'blockList')) FROM users;

Upvotes: 3

Imran
Imran

Reputation: 13458

SELECT array_agg(ks) FROM ( SELECT json_object_keys(friends->'blockList') AS ks FROM users ) x

I have created a SQL fiddle here to demonstrate.

Note: user is a reserved word, so I have called the table users.

Upvotes: 2

Marth
Marth

Reputation: 24812

Use json_object_keys to a set containing the outermost keys of a json object (so you'll need to select the object for the blockList key, which you can do with friends->'blockList'), and use array_agg to aggregate them into an array:

SELECT ARRAY_AGG(f) 
FROM (
  SELECT json_object_keys(friends->'blockList') f
  FROM users
) u;
┌───────────────────────┐
│       array_agg       │
├───────────────────────┤
│ {199,215,219,225,229} │
└───────────────────────┘
(1 row)

Note:
If you're using the jsonb type (and not the json one) you'll need to use the jsonb_object_keys function.

Upvotes: 16

Related Questions