You can use json_array_elements function to expand a JSON array into a set of rows, each containing one element of the array. It is a simpler option compared to complex looping logic. It is also more efficient than executing the same operation on the application side by reducing data transfer and processing overhead.
Function signature
json_array_elements example
Suppose you have a developers table with information about developers:
developers
Now, let's say you want to extract a row for each skill from the skills JSON array. You can use json_array_elements to do that:
This query returns the following result:
Advanced examples
This section shows advanced json_array_elements examples.
json_array_elements with nested data
Let's consider a scenario where we have a products table storing information about products. The table schema and data are provided below.
products
The json_array_elements function can be used to get all the combinations of size and color for a specific product. For example:
This query returns the following values:
Filtering json_array_elements
You can use the json_array_elements function to extract the sizes from the JSON data and then filter the products based on a specific color (or size), as in this example:
This query returns the following values:
Handling NULL in json_array_elements
This example updates the table to insert another product (Socks) with one of the values in the sizes as null:
products
Querying for Socks shows how null values in an array are handled:
This query returns the following values:
Nested arrays in json_array_elements
You can also handle nested arrays with json_array_elements.
Consider a scenario where each product has multiple variants, and each variant has an array of sizes and an array of colors. This example uses an elecronics_products table, shown below.
electronics_products
To handle the nested arrays and extract information about each variant, you can use the json_array_elements function like this:
This query returns the following values:
Additional considerations
This section outlines additional considerations including alternative functions and JSON array order.
Alternates to json_array_elements
jsonb_array_elements - Consider this variant for performance benefits with jsonb data. jsonb_array_elements only accepts jsonb data, while json_array_elements works with both json and jsonb. It is typically faster, especially for larger arrays, due to its optimization for the binary jsonb format.
json_array_elements_text - While json_array_elements returns each extracted element as a JSON value, json_array_elements_text returns each extracted element as a plain text string.
Ordering json_array_elements output using WITH ORDINALITY
If the order of the elements is important, consider using the WITH ORDINALITY option:
This query returns the following values:
The WITH ORDINALITY option in the query adds an ordinality column representing the original order of the skills in the array.