Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

PostgreSQL Error 22039: SQL JSON Array Not Found Fix

· 6 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

PostgreSQL error 22039 occurs when a query attempts to access a JSON array element using a path or operator that does not exist or is incorrectly formatted for the data type. To fix this, you must ensure you are using the integer-based index operator (#> or #>{index}) for arrays rather than the text-based key operator (> or #>{'key'}) which is reserved for JSON objects.

What You'll Need

  • Access to a PostgreSQL database (version 9.4 or higher for JSONB support).
  • A SQL client or terminal (such as psql, pgAdmin, or DBeaver).
  • Knowledge of the specific table and column containing the JSON/JSONB data.
  • The exact JSON structure of the record causing the error.

Step-by-Step

  1. Identify the Failing Query: Locate the exact SQL statement triggering the 22039 error. This usually happens during a SELECT statement where you are extracting a value from a JSONB column using a path operator. Look for the use of the #> operator or the jsonb_extract_path function.
  2. Inspect the JSON Data Structure: Before changing the query, verify if the target data is actually an array ( ) or an object ( {...} ). Run a simple SELECT column_name FROM table_name LIMIT 1; to see the raw JSON. If the value starts with a square bracket, it is an array. If it starts with a curly brace, it is an object.
  3. Correct the Operator Usage: If you are trying to access the first element of an array, do not use a string key.
    • Incorrect: SELECT data#>'{0}' FROM table; (Using a string '0' often fails or returns null depending on the version).
    • Correct: SELECT data#>'{0}' FROM table; (Ensure the path is passed as a text array of indices).
    • Alternative: Use the -> operator for a single level. For an array, data->0 retrieves the first element.
  4. Validate the Path Depth: Error 22039 often triggers when the path provided is deeper than the actual JSON structure. If your path is #>'{users, 0, name}' but the users array is empty or the index 0 does not exist, the operation may fail or return an unexpected result. Use jsonb_array_length(column) to verify the array has elements before attempting to access a specific index.
  5. Cast Data Types Explicitly: Ensure the column is defined as JSONB rather than JSON. The JSONB type is processed as a binary format and supports more efficient indexing and path operations. If your column is JSON, cast it using column_name::jsonb before applying path operators.
  6. Test with a Controlled Subset: Run the corrected query on a single row using a WHERE clause to ensure the syntax is correct for that specific JSON blob. For example: SELECT data->0 FROM table WHERE id = 123;.
  7. Implement Null Handling: To prevent the query from failing when an array is missing or empty, wrap the extraction in a COALESCE function or use a CASE statement to check if the element exists.

Common Mistakes

One of the most frequent mistakes is confusing the -> operator with the ->> operator. The -> operator returns a JSON object or array, while ->> returns the value as text. If you use ->> on a path that doesn't exist in an array, you might get a null value, but if the path logic itself is malformed (treating an array as an object), you will encounter error 22039.

Another common error is using 1-based indexing. PostgreSQL JSON arrays are 0-indexed. Attempting to access data->1 to get the first element will actually retrieve the second element. If the array only has one item, this will return null, and subsequent operations on that null value (like trying to extract a field from it) will trigger path errors.

Developers also frequently forget that JSON paths in PostgreSQL are case-sensitive. If you are accessing an object inside an array (e.g., data#>'{0, Name}') but the key is actually 'name' (lowercase), the path will not be found. While this usually returns NULL, in complex nested functions or strict constraints, it can lead to the 22039 error state.

Tips

To avoid these errors in the future, always use the jsonb_typeof() function when dealing with dynamic data. This allows you to check if the data is an 'array' or 'object' before applying the corresponding operator. This is especially useful in stored procedures or triggers where the incoming JSON might vary in structure.

For high-performance queries on JSON arrays, consider using GIN (Generalized Inverted Index) indexes. While an index won't stop a syntax error, it allows you to use the @> (contains) operator, which is often more robust than path-based extraction. Instead of searching for data#>'{0, id}' = '123', you can search for data @> '[{"id": "123"}]', which checks for the existence of the element regardless of its position in the array.

When working with deeply nested arrays, utilize the jsonb_array_elements() function to expand the array into a set of rows. This transforms the JSON array into a relational format, allowing you to use standard WHERE clauses and JOIN operations, which are much easier to debug than long path strings.

Troubleshooting

If you have corrected the operator and are still seeing the error, follow these steps in order:

First, check for hidden characters or whitespace in your JSON keys. Sometimes data imported from external APIs contains leading or trailing spaces (e.g., " name" instead of "name"). Use jsonb_each() to list all keys in the object and verify their exact spelling.

Second, verify the PostgreSQL version. Some JSONB operators and path behaviors were refined in versions 12 and 13. If you are on an older version (like 9.6), certain shorthand notations for array access may not be supported, requiring you to use the more verbose jsonb_extract_path() function.

Third, check for NULL values in the column. If the column itself is NULL, the path operator will return NULL. However, if the column contains the string "null" (a JSON null), the behavior differs. Use IS NOT NULL in your WHERE clause to filter out empty records before processing the JSON path.

Finally, if the error persists during a UPDATE or INSERT statement, check if you have any CHECK constraints on the column. A constraint that validates the JSON structure using a path may be triggering the 22039 error when you try to save a record that doesn't match the expected array format.

Frequently Asked Questions

What is the difference between -> and #>?

The -> operator is used for single-level access (either by key for objects or index for arrays). The #> operator is used for multi-level path access, taking a text array as an argument to navigate deep into the JSON structure.

Why does my query return NULL instead of error 22039?

In most standard SELECT queries, PostgreSQL returns NULL if a path is not found. Error 22039 typically occurs when the operation is performed within a function or a context where a specific data type is strictly expected, or when the path syntax is fundamentally incompatible with the data type (e.g., treating a scalar value as an array).

How do I find the length of a JSON array?

Use the jsonb_array_length(column) function. This is critical for preventing errors; you should check that the length is greater than the index you are trying to access.

Can I use a variable for the array index?

Yes, but you cannot pass a variable directly into the #> curly brace notation. You must construct the path array using ARRAY[variable]::text[] or use the -> operator with the integer variable.

Is JSONB always better than JSON?

For almost all use cases involving searching or extracting data, JSONB is superior because it is stored in a decomposed binary format, allowing for indexing and faster access. JSON is only preferable if you need to preserve the exact whitespace and key ordering of the original input.