Extract and Transform JSON Values with SQL/JSON Path Expressions
The JSON_QUERY() function in PostgreSQL 17 provides a powerful way to extract and transform JSON values using SQL/JSON path expressions. This function offers fine-grained control over how JSON values are extracted and formatted in the results.
Use JSON_QUERY() when you need to:
Extract specific values from complex JSON structures
Handle multiple values in results
Control JSON string formatting
Handle empty results and errors gracefully
Function signature
The JSON_QUERY() function uses the following syntax:
Understanding Wrappers and Quotes
Wrapper Behavior
By default, JSON_QUERY() does not wrap results (equivalent to WITHOUT WRAPPER). There are three wrapper modes:
WITHOUT WRAPPER (default):
Returns unwrapped values
Throws an error if multiple values are returned
WITH UNCONDITIONAL WRAPPER (same as WITH WRAPPER):
Always wraps results in an array
Even single values are wrapped
WITH CONDITIONAL WRAPPER:
Only wraps results when multiple values are present
Single values remain unwrapped
Quote Behavior
For scalar string results:
By default, values are surrounded by quotes (making them valid JSON)
KEEP QUOTES: Explicitly keeps quotes (same as default)
OMIT QUOTES: Removes quotes from the result
Cannot use OMIT QUOTES with any WITH WRAPPER option
Example usage
Let's explore these behaviors using a sample dataset:
Working with single values
Working with multiple values
Using conditional wrapper
Quote handling
Using the PASSING clause
Handling empty results
Error handling examples
Common use cases
Data transformation
Performance considerations
Use appropriate options:
Use RETURNING TEXT with OMIT QUOTES when JSON formatting is not required
Choose CONDITIONAL WRAPPER over UNCONDITIONAL when possible
Consider using DEFAULT expressions for better error recovery
Optimization tips:
Create indexes on frequently queried JSON paths
Use specific path expressions instead of wildcards when possible