Postgres JSON_VALUE() Function
newExtract and Convert JSON Scalar Values
The JSON_VALUE()
function in PostgreSQL 17 provides a specialized way to extract single scalar values from JSON
data with type conversion capabilities. This function is particularly useful when you need to extract and potentially convert individual values from JSON
structures while ensuring type safety and proper error handling.
Use JSON_VALUE()
when you need to:
- Extract single scalar values from
JSON
- Convert
JSON
values to specific PostgreSQL data types - Ensure strict type safety when working with
JSON
data - Handle missing or invalid
JSON
values gracefully
Function signature
The JSON_VALUE()
function uses the following syntax:
Parameters:
context_item
:JSON/JSONB
input to processpath_expression
:SQL/JSON
path expression that identifies the value to extractPASSING
: Optional clause to pass variables into the path expressionRETURNING
: Specifies the desired output data type (defaults to text)ON EMPTY
: Handles cases where no value is foundON ERROR
: Handles extraction or conversion errors
Example usage
Let's explore various ways to use the JSON_VALUE()
function with different scenarios and options.
Basic value extraction
Type conversion with RETURNING
Using variables with PASSING
Error handling
Working with nested structures
Common use cases
Data validation
Error handling
The function provides several ways to handle errors:
-
Using
ON EMPTY
:ERROR
: Raises an error (default)NULL
: ReturnsNULL
DEFAULT expression
: Returns specified value
-
Using
ON ERROR
:ERROR
: Raises an error (default)NULL
: ReturnsNULL
DEFAULT expression
: Returns specified value
JSON_VALUE vs JSON_QUERY
The JSON_VALUE()
function is designed for extracting scalar values from JSON
data, while JSON_QUERY()
is used for extracting JSON
structures (objects, arrays, or scalar values). Here's a comparison of the two functions:
Purpose and Return Types
JSON_VALUE()
:
- Designed specifically for extracting scalar values (numbers, strings, booleans)
- Always returns a single scalar value as text (or specified type via
RETURNING
) - Removes quotes from string values by default
- Throws an error if the result is an object or array
JSON_QUERY()
:
- Designed for extracting
JSON
structures (objects, arrays, or scalar values) - Returns valid
JSON/JSONB
output - Preserves quotes on string values by default
- Can handle multiple values using wrapper options
Example Comparisons
Additional considerations
-
Type safety:
- Always use
RETURNING
when specific data types are expected - Implement appropriate error handling for type conversions
- Always use
-
Performance considerations:
- Use indexes on frequently queried
JSON
paths
- Use indexes on frequently queried