Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get array of all json field keys in postgresql

Tags:

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.

like image 789
Amjad Omari Avatar asked Apr 12 '16 14:04

Amjad Omari


3 Answers

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;
like image 110
Anton Bessonov Avatar answered Sep 22 '22 11:09

Anton Bessonov


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.

like image 20
Marth Avatar answered Sep 24 '22 11:09

Marth


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.

like image 24
Imran Avatar answered Sep 21 '22 11:09

Imran