PostgreSQL – JSON_OBJECT_KEYS Function

You can use the json_object_keys function to extract the keys (field names) from a JSON object in PostgreSQL database. This function takes a JSON object as its argument and returns a set of text values representing the keys in the JSON object.

Here is the basic syntax for the json_object_keys function:

sqlCopy code

json_object_keys(json_object)

where json_object is the JSON object from which you want to extract the keys.

Here’s an example of using the json_object_keys function:

Suppose you have a JSON object stored in a PostgreSQL table like this:

{ "name": "John Doe", "age": 30, "email": "johndoe@example.com" }

You can use the json_object_keys function to extract the keys from this JSON object:

SELECT json_object_keys('{ "name": "John Doe", "age": 30, "email": "johndoe@example.com" }'::json) AS keys;

The result of this query will be a set of keys:

| keys | 
|--------| 
| name | 
| age | 
| email |

In this example:

  • We’ve used the ::json cast to explicitly specify that the input is a JSON object.
  • The json_object_keys function is applied to the JSON object, and it returns a set of keys as text values.

You can use the result of json_object_keys in various ways, such as iterating through the keys or using them to access specific values within the JSON object. This function is especially useful when working with JSON data in PostgreSQL and need to perform operations based on the keys present in JSON objects.

Similar Posts