19

Is it possible to return a JSON object keys as an array of values in PostgreSQL?

In JavaScript, this would simply be Object.keys(obj), which returns an array of strings.

For example, if I have a table like this:

tbl_items
---------
id bigserial NOT NULL
obj json NOT NULL

And if there's a row like this:

id obj
----- -------------------------
123 '{"foo":1,"bar":2}'

How can I have a query to return:

id keys
----- ------------------
123 '{"foo","bar"}'
Erwin Brandstetter
186k28 gold badges463 silver badges636 bronze badges
asked Jan 25, 2016 at 14:51
1

1 Answer 1

34

json_object_keys() (or jsonb_object_keys() for jsonb) returns a set - unlike the JavaScript function Object.keys(obj) you are referring to, which returns an array. Feed the set to an ARRAY constructor to transform it:

SELECT id, ARRAY(SELECT json_object_keys(obj)) AS keys
FROM tbl_items;

This returns an array of keys per row (not for the whole table).

A more verbose form would be to spell out a LATERAL join instead of the correlated subquery:

SELECT t.id, k.keys
FROM tbl_items t
LEFT JOIN LATERAL (
 SELECT ARRAY(
 SELECT * FROM json_object_keys(t.obj)
 )
 ) k(keys) ON true;
answered Jan 25, 2016 at 15:02
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.