PostgreSQL jsonb_object_keys() Function
Summary: in this tutorial, you will learn how to use the PostgreSQL jsonb_object_keys()
function to extract the keys from a JSON object.
Introduction to the PostgreSQL jsonb_object_keys() function
The jsonb_object_keys()
function allows you to extract the keys of a JSON object into a set of text values.
Here’s the basic syntax of the jsonb_object_keys()
function:
In this syntax:
json_object
is the JSON object of type JSONB that you want to extract the keys.
The jsonb_object_keys()
function returns a set of text values representing the keys in the json_object
.
If the json_object
is not a JSON object, the jsonb_object_keys()
function will issue an error.
If the json_object
is NULL
, the function will return an empty set.
PostgreSQL jsonb_object_keys() function examples
Let’s take some examples of using the jsonb_object_keys()
function.
1) Basic the jsonb_object_keys() function examples
The following example uses the jsonb_object_keys()
function to extract the keys of a JSON object as a set of text values:
Output:
2) Using the PostgreSQL jsonb_object_keys() function with table data
First, create a table called person
:
In the person
table, the info
column has the type JSONB that stores various information about each person.
Second, insert rows into the person
table:
Third, get the keys of the objects in the info
column:
Output:
To get unique keys from all the stored JSON objects in the info column, you can use the DISTINCT
operator:
Output:
3) Dynamically accessing keys
The following example shows how to dynamically access values corresponding to each key retrieved using jsonb_object_keys()
:
Output:
In this example, the query returns each key along with its corresponding value from the info
column of the person
table.
Summary
- Use the
jsonb_object_keys()
function to extract the keys from a JSON object.